MyBatis entry (a) - Getting Case

A, MyBatis Profile

  MyBatis is sql-oriented persistence framework, he encapsulates the process jdbc access to the database, we have developed, just focus on the assembled sql statement itself, other processes can all be assigned to the MyBatis to complete.

  Compared with Hibernate:

1.Hibernate learning threshold is not low, to master a higher threshold. How to design a high threshold in O / R mapping, how to weigh the balance between performance and object model, and how to make good use of Hibernate cache and data loading strategies need your experience and capabilities are strong for the job. The current domestic situation before hibernate technical proficiency Daniel is very small.

2.sql optimization, Hibernate query all the fields in the table will check out, this performance will be consumed. Of course, Hibernate can also write your own SQL query to specify the fields that need, but it undermines the simplicity Hibernate development. Said more deeply, if there is a query to be associated with more than one table, such as 5 tables, 10 tables, and the fields we have to take only part of the field where a few tables. Then when using hibernate will seem very inadequate. Even with sqlquery hibernate, and follow-up maintenance work will make people mad.

Second, the introductory case

1, the database is ready (create table statement)

 
 1 -- ----------------------------
 2 -- Table structure for `user`
 3 -- ----------------------------
 4 DROP TABLE IF EXISTS `user`;
 5 CREATE TABLE `user` (
 6   `id` int(11) NOT NULL AUTO_INCREMENT,
 7   `username` varchar(32) NOT NULL COMMENT '用户名称',
 8   `birthday` date DEFAULT NULL COMMENT '生日',
 9   `sex` char(1) DEFAULT NULL COMMENT '性别',
10   `address` varchar(256) DEFAULT NULL COMMENT '地址',
11   PRIMARY KEY (`id`)
12 ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
13 
14 -- ----------------------------
15 -- Records of user
16 -- ----------------------------
17 INSERT INTO `user` VALUES ( ' 1', ' Wang Wu', null, '2', null);
18 INSERT INTO `user` VALUES ( ' 10', ' John Doe', '2014-07-10', '1', 'Beijing'); 
. 19 the INSERT the INTO` user` the VALUES ( '16', 'Xiaoming' , null, '1', 'Zhengzhou'); 
20 is the INSERT the INTO `user` the VALUES ( '22 is',' John Doe ', null,' 1 ', ' Zhengzhou '); 
21 is the INSERT the INTO` user` the VALUES (' 24 ',' Chi Master ', null,' 1 ', ' Zhengzhou '); 
22 is the INSERT the INTO `user` the VALUES (' 25 ',' John Doe ', null,' 1 ', ' Zhengzhou '); 
23 is the INSERT the INTO `user` VALUES ( '26', ' Wang Wu', null, null, null) ;
 

2, using the new idea maven-archetype-quickstart projects

3, dependent on the introduction of

 
 1 <dependency>
 2       <groupId>mysql</groupId>
 3       <artifactId>mysql-connector-java</artifactId>
 4       <version>5.1.45</version>
 5 </dependency>
 6 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
 7 <dependency>
 8       <groupId>org.mybatis</groupId>
 9       <artifactId>mybatis</artifactId>
10       <version>3.2.7</version>
11 </dependency>
 

4. Create a folder SqlMapConfig.xml in resources

 
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <!-- 和spring整合后 environments配置将废除 -->
 7     <environments default="development">
 8         <environment id="development">
 9             <!-- 使用jdbc事务管理 -->
10             <transactionManager type="JDBC" />
11             <!-- 数据库连接池 -->
12             <dataSource type="POOLED">
13                 <property name="driver" value="com.mysql.jdbc.Driver" />
14                 <property name="url"
15                           value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
31 <- <! package name = "com.cenobitor.mapper" />
16 <Property name = "username" value = "the root" /> 
. 17 <Property name = "password" value = "" /> 
18 is </ the dataSource> 
. 19 </ Environment> 
20 is </ Environments> 
21 is 
22 is <by mappers> 
23 is <! - a first way, loading Resource -> 
24 <Resource Mapper = "User.xml"> </ Mapper> 
25 <Resource Mapper = "UserMapper.xml" /> 
26 is 
27 <! - third embodiment, the package requires a scanner (this method is recommended): 
281, map files in the same directory interface 
292, the interface map file name with the file names required for consistent 
30 -> 
32 </ by mappers> 
33 is </ Configuration>
 

5, create entity classes User

 
Package com.cenobitor.pojo. 1; 
 2 
 . 3 Import java.util.Date; 
 . 4 
 . 5 the User {public class 
 . 6 
 . 7 Private ID Integer; 
 . 8 String Private username; // name of the user 
 9 private String sex; // Gender 
10 private Date birthday ; // birthday 
11 private String address; // address 
12 is UUID String Private; 
13 is 
14 ...... 
15}
Copy the code

6, configure SQL query mapping file (resources directory)

Copy the code
. 1 <XML Version = "1.0" encoding = "UTF-. 8"??> 
 2 <DOCTYPE Mapper! 
 . 3 the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" 
 . 4 "http://mybatis.org /dtd/mybatis-3-mapper.dtd "> 
 . 5 <- namespace:! namespace, analogous java package, primarily to isolate the sql statement, an important role in the subsequent 
 6 # {}: placeholder, equivalent the jdbc? 
 7} {$: string concatenation instruction, if the note is a common data type parameter, which can only be written in parentheses value 
 . 8 -> 
 . 9 <Mapper namespace = "User"> 
10 <- ID:! SQL id identifies uniquely identifies the sql statement 
11 parameterType: reference data types into 
12 resultType: returns the result of the data type 
13 is -> 
14 <SELECT id = "getUserById" the parameterType = "int" = the resultType "com.cenobitor.pojo.User ">
15         SELECT
16           `id`,
17           `username`,
`Birthday` 18 is, 
. 19` sex`, 
20 is `address` 
21 is the FROM` user` 
22 is the WHERE ID = # {ID} 
23 is </ SELECT> 
24 
25 <- the resultType:! If the result is set, only need to set type of the data element can -> 
26 is <SELECT ID = "getUserByName" the parameterType = "String" the resultType = "com.cenobitor.pojo.User"> 
27 the SELECT 
28 `id`, 
29` username`, 
30 `Birthday `, 
31 is` sex`, 
32 `address` 
33 is the FROM` user` 
34 is the WHERE username the LIKE '% $ {value}%' 
35 </ SELECT> 
36      
37 [<INSERT ID = "insertUser"parameterType="com.cenobitor.pojo.User">
The USER the INSERT the INTO 38 is (username` `,` birthday`, sex` `,` address`) 
39 the VALUES (# {username}, {#} Birthday, Sex # {}, {address} #) 
40 </ INSERT> 
41 is 
42 <! - returns MySql increment primary key -> 
43 is <- useGeneratedKeys:! insert using self-energizing identification ID 
44 is the keyProperty: using useGeneratedKeys supporting pojo for binding the primary key attribute received 
45 -> 
46 is <iNSERT = ID "insertUserKey" the parameterType = "com.cenobitor.pojo.User" 
47 useGeneratedKeys = "to true" the keyProperty = "ID"> 
48 
49 <- the selectKey:! configure the master key to return 
50 keyProperty: property to be bound pojo 
51 resultType: property data type 
52 order:After you specify when to perform, an AFTER 
53 ->
54 is <-! <The selectKey the keyProperty = "ID" the resultType = "int" Order = "an AFTER"> 
55 the LAST_INSERT_ID the SELECT () 
56 is </ the selectKey> -> 
57 is 
58 the INSERT the INTO the USER (username` `,` birthday`, sex` `,` address`) 
59 the VALUES (# {username}, {#} Birthday, Sex # {}, {address} #) 
60 </ INSERT> 
61 is 
62 is <-! MySql is returned back to the main key uuid - > 
63 is <INSERT ID = "insertUserUUID" the parameterType = "com.cenobitor.pojo.User"> 
64 
65 <- the selectKey:! configure the master key to return 
66 keyProperty: pojo property to bind 
67 resultType: property data type 
68 order:After you specify when to perform, an AFTER 
69 ->
70         <selectKey keyProperty="uuid" resultType="String" order="BEFORE">
71              SELECT UUID()
72         </selectKey>
73 
74         INSERT INTO USER (`username`,`birthday`,`sex`,`address`,`uuid`)
75         VALUES (#{username},#{birthday},#{sex},#{address},#{uuid})
76     </insert>
77     
78     <update id="updateUser" parameterType="com.cenobitor.pojo.User">
79         UPDATE USER SET username = #{username} WHERE id = #{id}
80     </update>
81     
82     <delete id="deleteUser" parameterType="com.cenobitor.pojo.User">
83         DELETE FROM `user` WHERE `id` = #{id}
84     </delete>
85 
86 </mapper>
 

7, load map files, configuration mappers node SqlMapConfig.xml

8, write test classes

 
  1 package com.cenobitor;
  2 
  3 import com.cenobitor.Utils.SqlSessionFactoryUtils;
  4 import com.cenobitor.pojo.User;
  5 import junit.framework.Test;
  6 import junit.framework.TestCase;
  7 import junit.framework.TestSuite;
  8 import org.apache.ibatis.io.Resources;
  9 import org.apache.ibatis.session.SqlSession;
 10 import org.apache.ibatis.session.SqlSessionFactory;
 11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 12 
 13 import java.io.IOException;
 14 import java.io.InputStream;
 15 import java.util.Date;
 16 import java.util.List;
 17 
 18 /**
 19  * Unit test for simple App.
 * 20 is / 
 21 is the AppTest the extends TestCase {public class 
 22 is based on the id // Find user 
 23 is testGetUserById public void () throws IOException { 
 24 
 25 // create objects SqlSessionFactoryBuilder 
 26 is SqlSessionFactoryBuilder new new SqlSessionFactoryBuilder SFB = (); 
 27 // find the configuration file, creating the input stream 
 28 inputStream = Resources.getResourceAsStream the inputStream ( "the SqlMapConfig.xml"); 
 29 // load the configuration file, creating a SqlSessionFactory 
 30 a SqlSessionFactory SqlSessionFactory = sfb.build (inputStream); 
 31 is // Create the SqlSession 
 32 sqlSessionFactory.openSession the SqlSession SQLSESSION = ( ); 
 33 // execute the query, a parameter: statementId to query, two parameters: sql statement to the Senate
 The User User sqlSession.selectOne = 34 is ( "user.getUserById",. 1); 
 35 // input query result 
 36 System.out.println (User); 
 37 [ 
 38 is to release resources // 
 39 sqlSession.close (); 
 40} 
 41 is 
 42 is // Find the list of users based on the user name 
 43 is testGetUserByName public void () { 
 44 is a SqlSessionFactory SqlSessionFactoryUtils.getSqlSessionFactory SqlSessionFactory = (); 
 45 sqlSessionFactory.openSession the SqlSession SQLSESSION = (); 
 46 is list <the user> sqlSession.selectList list = ( "user.getUserByName "" Zhang "); 
 47 for (the User User: List) { 
 48 System.out.println (User); 
 49} 
 50
 SqlSession.close 51 is (); 
 52 is} 
 53 is 
 54 is inserted into the user // 
 55 testInsertUser public void () { 
 56 is a SqlSessionFactory SqlSessionFactoryUtils.getSqlSessionFactory SqlSessionFactory = (); 
 57 is the SqlSession SQLSESSION sqlSessionFactory.openSession = (); 
 58 
 59 = the User new new User the User ( ); 
 60 user.setUsername ( "Diao"); 
 61 is user.setSex ( "0"); 
 62 is user.setBirthday (new new a Date ()); 
 63 is user.setAddress ( "Bu"); 
 64 
 65 // execute insert statements 
 sqlSession.insert 66 ( "user.insertUser", the User); 
 67 // commit the transaction 
 68 sqlSession.commit (); 
 69 // release resources
 SqlSession.close 70 (); 
 71 is} 
 72 
 73 is incremented // return Mysql 
 74 testInsertUserKey public void () { 
 75 = a SqlSessionFactory SqlSessionFactory SqlSessionFactoryUtils.getSqlSessionFactory (); 
 76 sqlSessionFactory.openSession the SqlSession SQLSESSION = (); 
 77 
 78 = the User new new User the User (); 
 79 user.setUsername ( "Yang Yuhuan"); 
 80 user.setSex ( "0"); 
 81 user.setBirthday (new new a Date ()); 
 82 user.setAddress ( "Longji"); 
 83 
 84 / / execute insert statement 
 85 sqlSession.insert ( "user.insertUserKey", the User); 
 86 System.out.println (the User); 
 87 // commit the transaction
 SqlSession.commit 88 (); 
 89 // release resources 
 90 sqlSession.close (); 
 91 is} 
 92 
 93 // Mysql to return to the main key uuid 
 94 // Note: Before using uuid database together with the user table uuid2 first field, user also with the corresponding properties of pojo 
 95 testInsertUserUUID public void () { 
 96 = a SqlSessionFactory SqlSessionFactory SqlSessionFactoryUtils.getSqlSessionFactory (); 
 97 sqlSessionFactory.openSession the SqlSession SQLSESSION = (); 
 98 
 99 = the User User the User new new (); 
100 user.setUsername ( "Shangxiang"); 
101 user.setSex ( "0"); 
102 user.setBirthday (new new a Date ()); 
103 user.setAddress ( "Bei"); 
104 
105 // execute insert statements
SqlSession.insert 106 ( "user.insertUserUUID", User); 
107 System.out.println (User); 
108 // commit the transaction 
109 sqlSession.commit (); 
110 // release resources 
111 sqlSession.close (); 
112} 
113 
114 // modify user 
115 testUpdateUser public void () { 
1 16 = a SqlSessionFactory SqlSessionFactory SqlSessionFactoryUtils.getSqlSessionFactory (); 
117 = the SqlSession SQLSESSION sqlSessionFactory.openSession (); 
1 18 
119 the user user the user new new = (); 
120 user.setUsername ( "Lu pheasant "); 
121 user.setId (32); 
122 
123 // execute insert statements
124         sqlSession.update("user.updateUser",user);
125 
126         //提交事务
127         sqlSession.commit();
128         //释放资源
129         sqlSession.close();
130     }
131 
132     //删除用户
133     public void testDeleteUser(){
134         SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
135         SqlSession sqlSession = sqlSessionFactory.openSession();
136         sqlSession.delete("user.deleteUser",32);
137         sqlSession.commit();
138         sqlSession.close();
139     }
140 }
 

9, SqlSessionFactoryUtils extraction tools, shared object SqlSessionFactory

 
 1 public class SqlSessionFactoryUtils {
 2     private SqlSessionFactoryUtils(){}
 3 
 4     private static class SqlSessionFactoryInstance{
 5 
 6         public static SqlSessionFactory sqlSessionFactory;
 7 
 8         static {
 9             try {
10                 sqlSessionFactory =  new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
11             } catch (IOException e) {
12                 e.printStackTrace();
13             }
14         }
15     }
16 
17     public static SqlSessionFactory getSqlSessionFactory(){
18         return SqlSessionFactoryInstance.sqlSessionFactory;
19     }
20 
21 }
 

Three, MyBatis Chart

Four, MyBatis dynamic development agency Dao 

 1, the development rules

  • namespace must be the full path name of the interface
  • The interface method name must match the sql id mapping file
  • Input parameters of the interface must be consistent with parameterType type mapping file
  • The return type interface must be consistent with the type of map file resultType

2, dynamic proxy Dao development steps

① create a map file UserMapper.xml

 
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.cenobitor.mapper.UserMapper">
 6 
 7     <select id="getUserById" parameterType="int" resultType="com.cenobitor.pojo.User">
 8         SELECT
 9           `id`,
10           `username`,
11           `birthday`,
12           `sex`,
13           `address`
14         FROM `user`
15         WHERE id = #{id}
16     </select>
17 
18     <select id="getUserByName" parameterType="String" resultType="com.cenobitor.pojo.User">
19         SELECT
20           `id`,
21           `username`,
22           `birthday`,
23           `sex`,
24           `address`
25         FROM `user`
26         WHERE username LIKE '%${value}%'
27     </select>
28     
29     <insert id="insertUser" parameterType="com.cenobitor.pojo.User">
30         INSERT INTO USER (`username`,`birthday`,`sex`,`address`)
31         VALUES (#{username},#{birthday},#{sex},#{address})
32     </insert>
33 
34 </mapper>
 

② create UserMapper Interface

 
Package com.cenobitor.mapper. 1; 
 2 
 . 3 Import com.cenobitor.pojo.User; 
 . 4 Import java.util.List; 
 . 5 
 . 6 UserMapper {public interface 
 . 7 
 . 8 / ** querying user based on the user ID information 
 . 9 * @param ID 
10 @return * 
. 11 * / 
12 is the user getUserById (ID Integer); 
13 is 
14 / ** 
15 * Find a user based on the user name list 
16 * @param name 
. 17 * @return 
18 is * / 
. 19 list <the user> getUserByName (String name); 
20 is 
21 / ** 
22 * add user 
23 is @param user * 
24 * / 
25 void insertUser (the user user); 
26 is 
27}
 

③ load UserMpper.xml

 

④ create a test class

 
 1 public class UserMapperTest {
 2 
 3     @Test
 4     public void getUserById() {
 5         SqlSessionFactory sqlSessionFactory =
 6                 SqlSessionFactoryUtils.getSqlSessionFactory();
 7         SqlSession sqlSession = sqlSessionFactory.openSession();
 8         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
 9         User user = mapper.getUserById(31);
10         System.out.println(user);//User{id=31, username='杨玉环', sex='0', birthday=Sat Apr 07 00:00:00 CST 2018, address='李隆基', uuid='null'}
11         sqlSession.close();
12     }
13 
14     @Test
15     public void getUserByName() {
16         SqlSessionFactory sqlSessionFactory =
17                 SqlSessionFactoryUtils.getSqlSessionFactory();
18         SqlSession sqlSession = sqlSessionFactory.openSession();
19         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
20         List<User> users = mapper.getUserByName("张");
21         for (User user : users) {
22             System.out.println(user);
23         }
24         /*User{id=10, username='张三', sex='1', birthday=Thu Jul 10 00:00:00 CST 2014, address='北京市', uuid='null'}
25         User{id=16, username='张小明', sex='1', birthday=null, address='河南郑州', uuid='null'}
26         User{id=24, username='张三丰',sex = '1', birthday = null, address = 'Zhengzhou', uuid = 'null'} * /
27         sqlSession.close();
28     }
29 
30     @Test
31     public void insertUser() {
32         SqlSessionFactory sqlSessionFactory =
33                 SqlSessionFactoryUtils.getSqlSessionFactory();
34         SqlSession sqlSession = sqlSessionFactory.openSession();
35         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
36         User user = new User();
37         user.setUsername("lisi");
38         user.setSex("1");
39         user.setBirthday(new Date());
40         user.setAddress("北京");
41         mapper.insertUser(user);
42         sqlSession.commit();
43         sqlSession.close();
44     }
45 }
 

Five, SqlMapConfig.xml configuration

1、properties

① belong to the core configuration file

1 <! - loading rule, first loads the internal tag attributes, and then load the external file with the same name will replace the contents of the same name -> 
2 <Properties Resource = "the jdbc.properties"> 
. 3 <Property name = "JDBC .username "value =" the root1 "/> 
. 4 <Property name =" jdbc.password "value =" the root "/> 
. 5 </ Properties>

②jdbc.properties

1     jdbc.driver=com.mysql.jdbc.Driver
2     jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
3     jdbc.username=root
4     jdbc.password=root

2、typeAliases

Custom aliases

 
. 1 <typeAliases> 
2 <-! Single alias definition -> 
. 3 <-! <TypeAlias type = "com.itheima.mybatis.pojo.User" Alias = "User" /> -> 
. 4 <! - alias scanner package (this method is recommended), the entire class packets are defined alias, the class name insensitive -> 
. 5 <package name = "com.itheima.mybatis.pojo" /> 
. 6 </ typeAliases>
 

3、mapper

 
. 1 <by mappers> 
 2 <-! A first embodiment, loading Resource -> 
 . 3 <Resource Mapper = "Mapper / the user.xml." /> 
 . 4 <-! <Resource Mapper = "Mapper / UserMapper.xml" / > -> 
 5 
 ! 6 <- second embodiment, the scanner class requirements: 
 71, map file directory of the same interface 
 82, the interface map file name with the file names required for consistent 
 9 -> 
10 <-! - <Mapper class = "com.itheima.mybatis.mapper.UserMapper" /> -> 
. 11 
12 is <- a third mode, the scanner requires package (this method is recommended):! 
131, the mapping document interface the same directory 
142, the interface map file name with the file names required for consistent 
15 -> 
16 <Package name = "com.itheima.mybatis.mapper" /> 
. 17 </ by mappers>
 

 VI Summary

1, and $ # {} {}

{#} Denotes a placeholder, may be implemented by the preparedStatement # {}, automatic type conversions java jdbc type and setting a value in the placeholder. {#} Sql injection can be effectively prevented. } # {Acceptable value or a simple type pojo attribute value. If the transmission of a single parameterType simple type values ​​# {} brackets may be a value or other name.

$ {} Represents splicing sql string} parameterType incoming content can not be spliced ​​sql jdbc type conversion by $ {,} $ {acceptable value or a simple type pojo attribute value, if the transmission of a single simple type values ​​parameterType , $ {} brackets only value.

2、parameterType和resultype

parameterType: specifies the input parameter type, mybatis parameter values ​​acquired from the input object by splicing ognl in the sql.

resultType: Object of the specified type. If a plurality of data, respectively, by mapping the object into a container and put in the List.

Guess you like

Origin www.cnblogs.com/liuys635/p/12565897.html