Introduction to Mybatis:
MyBatis is an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis. Migrated to Github in November 2013.
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, mapping interfaces and Java POJOs (Plain Old Java Objects) into records in the database.
1. The function of MyBatis:
Simply put, MyBatis implements the DAO layer, which configures SQL through XML files and maps to PO.
2. Quotation packages that need to be prepared
mybatis-3.2.8.jar: MyBatis framework is used
ojdbc6.jar: Database connection
Configuration of Mybatis environment (here is a separate configuration of mybatis):
First: Download and import of mybatis jar package
The download address of v3.4.5 is:
http://xiazai.VeVB.COM/201712/yuanma/mybatis-3.4.5.rar
If you don't want to use version 3.4.5, but if you forget the address, we can search directly on the official website of github.com: mybatis
The search results are shown in the figure:
Click Download Latest at this time, and then select the version you want to download.
Unzip the downloaded compressed package and import all the mybatis-3.4.5.jar and the jar in the lib folder into eclipse. Of course, at this time, you also need to import the jar package of mysql driver into mysql-connector-java-5.1.44.jar.
Because we did not use Maven here, the following configuration is not needed, because we have manually imported all the jars:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version></dependency>
2. Writing configuration files
Create a source folder in your own project, store your own configuration document and create sqlMappersConfig.xml, and copy the following configuration (the official configuration provided by the official, change the official configuration to your own):
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers></configuration>The configuration in sqlConnect.properties is as follows:
sqlDriver:com.mysql.jbdc.DriversqlUrl:mysql:jbdc://172.20.60.2/spectergk?useUnicode=true&characterEncoding=UTF8sqlUserName:testsqlUserPwd:1111111
OK So far, we have completed the basic configuration of config that needs to be configured, but this is just the configuration of config, test code:
public void functionTest(){ //System.out.println("Start mybatis"); InputStream inputStream = null; try {<br data-filtered="filtered"> inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * Create factory*/ SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /* * Open ssion */ SqlSession sqlSession = sqlSessionFactory.openSession(); System.out.println(sqlSession); sqlSession.close(); try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }At this time, the printing is a value that proves that we have successfully configured it, and we can set the mapper for the rest.
Second: the creation and use of mappers, because mybatis mapper can use dynamic proxy, and we directly use dynamic proxy here:
Create in the pojo package:
User.java
Create in mappers package:
UserMapper.java
Create in the same directory as sqlMappersConfig.xml:
User.xml
And configure the following code in sqlMappersConfig.xml:
<!--The following is alias the package name of com.spectergk.mybatis.pojo.User--!><typeAliases><typeAlias type="com.spectergk.mybatis.pojo.User" alias="User"/></typeAliases><!--Loading the mapping resource--!><mappers><mapper resource="User.xml"/></mappers>
Implement simple addition, deletion, modification and search of the database. The specific implementation is as follows:
User.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- The package pointed to by namespace is UserMapper interface This is one of the conditions for implementing dynamic proxy--><mapper namespace="com.spectergk.mybatis.mappers.UserMapper"><!- The return value configured here is User This is because its rename has been configured in sqlMappersConfig.xml--><!-- Query the user's return value according to the id used. The value passed by User is parameterType --> <select id="selectUserById" resultType="User" parameterType="String"> select * from user where uid = #{v} </select> <!-- Fuzzy query based on the user's user name-> <select id="selectUsersbyUserName" resultType="User" parameterType="String"> select * from user where realname like "%"#{v}"%"; </select> <!-- Insert data into the database--> <insert id="insertOneUser" parameterType="User"> INSERT into user(uid,username,realname,mobile,mainpid,sex) values(#{uid},#{username},#{realname},#{mobile},#{mainpid},#{sex}); </insert> <!-- The automatically generated uid that inserts data and returns --> <insert id="insertOneUserGetid" parameterType="User"> <selectKey keyProperty="uid" keyColumn="uid" resultType="String" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> INSERT into user(username,realname,mobile,mainpid,sex) values(#{username},#{realname},#{mobile},#{mainpid},#{sex}); </insert> <!-- Insert in list form--> <insert id="insetUsers" > INSERT into user(uid,username,realname,mobile,mainpid,sex) values <foreach collection="list" item="item" separator=","> (#{item.uid},#{item.username},#{item.realname},#{item.mobile},#{item.mainpid},#{item.sex}) </foreach> </insert> <!-- Insert as an array --> <insert id="insetUsersArray" > INSERT into user(uid,username,realname,mobile,mainpid,sex) values <foreach collection="array" item="item" separator=","> (#{item.uid},#{item.username},#{item.realname},#{item.mobile},#{item.mainpid},#{item.sex}) </foreach> </insert> <!-- Update user--> <update id="updateUser" parameterType="User"> UPDATE user set username = #{username} where uid = #{uid} </update> <!-- Delete user--> <delete id="deleteOneUser" parameterType="String"> delete from user where uid = #{v} </delete> <delete id="deleteMoreUsers"> delete from user where uid in ( <foreach collection="list" item="item" separator=","> #{item} </foreach> ) </delete></mapper>Because it is loading dynamically, just write the interface here:
package com.spectergk.mybatis.mappers;import java.util.List;import com.spectergk.mybatis.pojo.User;public interface UserMapper { /* * Query based on user id */ public User selectUserById(String id); /* * Fuzzy query based on user name */ public List<User> selectUsersbyUserName(String username); /* * Insert a user*/ public void insertOneUser(User user); /* * Insert a user and return the id of the inserted user */ public void insertOneUserGetid(User user); /* * Insert multiple users*/ public void insertUsers(List<User> users); /* * Insert multiple users to transmit array */ public void insertUsersArray(User[] users); /* * updateUser Update*/ public void updateUser(User user); /* * Delete one */ public void deleteOneUser(String uid); /* * deleteMoreUsers delete multiple */ public void deleteMoreUsers(List<String> uids);}Because of the test code, only fuzzy test code is written here:
//Query public void fuzzysearch(){ System.out.println("Start mybatis"); InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * Create factory*/ this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /* * Open ssion */ SqlSession sqlSession = this.sqlSessionFactory.openSession(); System.out.println(sqlSession); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.selectUsersbyUserName("Liu"); for (User user : users) { System.out.println(user); } sqlSession.close(); }Summarize
The above is the example code for the construction and use of Mybatis environment introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!