MyBatis framework Learning (III)-Mapper proxy development, mybatis-mapper

Source: Internet
Author: User

MyBatis framework Learning (III)-Mapper proxy development, mybatis-mapper
In the previous section, we learned the simple implementation of CRUD in MyBatis. In this process, we used the original Dao method for development. In this process, we found some drawbacks, if there are a lot of repeated code, sqlSession operations, and hard code of the id in statement, which may cause inconvenience to future maintenance, many programmers are also worried about this. Therefore, Mapper proxy development is recommended, which is simple and efficient, after all, the learning process is always bitter and sweet. next we will study er proxy development. i. The Mapper-based proxy development method is to use MyBatis to develop Dao. there are usually two methods, namely the original Dao method and the Mapper-based method. When MyBatis is developing Dao, generally, it involves three sisters: SqlSessionFactoryBuilder, SqlSessionFactiory, and SqlSession.
We all know that SqlSession encapsulates database operations, such as addition, deletion, modification, and query. SqlSession is created through SqlSessionFactory, and SqlSessionFactory is created by SqlSessionFactoryBuilder.
1. sqlSessionFactoryBuilder is used to create SqlSessionFacoty. Once created, SqlSessionFacoty does not need SqlSessionFactoryBuilder. Because SqlSession is produced through SqlSessionFactory, SqlSessionFactoryBuilder can be used as a tool, the best scope is the method scope, that is, the local variables in the method body.
2. sqlSessionFactory is an interface that defines different overload methods of openSession. The optimal range of use of SqlSessionFactory is that it can be reused once created during the entire application, sqlSessionFactory is usually managed in singleton mode.
3. SqlSession is a user-oriented interface that defines database operations. The DefaultSqlSession implementation class is used by default.
SqlSession provides many database operations Methods: selectOne (returns a single object) and selectList (returns a single or multiple objects). SqlSession is thread-insecure, in the SqlSesion implementation class, besides methods in the interface (methods used to operate databases) and data domain attributes, SqlSession is best used in the method body and defined as local variables, never put reference of a SqlSession instance in a static field or instance field of a class. In today's blog, I will focus on introducing the two methods for developing dao in mybatis, the original dao development method and mapper agent development.
The dao development methods in mybatis have their own advantages: the original dao development, the mapper agent development, the original Dao development, and the Mapper dynamic proxy development. Original Dao development: programmers need to write Dao and Dao implementation. They need a lot of code, but they are easy to understand. Mapper dynamic Proxy: programmers only need to write Mapper interfaces and configure them according to the specifications. MyBatis will automatically implement Dao-like implementation to reduce the template method. Mybatis officially recommends using mapper proxy to develop mapper interfaces. programmers do not need to write mapper interface implementation classes. When using mapper proxy methods, you can use pojo to wrap objects or map objects as input parameters, ensure the universality of dao.
Ii. Mapper proxy development: 1. Some Mapper proxy Development Rules * The namespace in xxxmapper. xml is equal to the mapper interface address
* The statement IDs in method xxxmapper. xml in the xxxmapper. java interface are consistent.
* The method input parameter in xxxmapper. java interface is the same as the parameterType specified in statement in xxxmapper. xml.
* The Return Value Type of the method in xxxmapper. java interface is the same as the type specified by resultType in xxxmapper. xml.
2. MyBatis Development Process
☐Compile the configuration file MyBatis-config.xml for MyBatis
☐Compile the MyBatis ing file xxxmapper. xml (here mainly statement and SQL statements)
☐Compile the interface method xxxmapper. java for MyBatis (note that the method name here is consistent with the statement in the ing file)
☐Obtain SqlSession through SqlSessionFactory
☐Use SqlSesson to operate the database (execute the SqlSession. commit () that CRUD needs to call ()
☐Close the database after using SqlSession
3. Create a user database

use mybatis;create table user(id int null auto_increment,name varchar(32) not null,
password varchar(32) not null,age int not null,create_time datetime null,primary key(id));

4. Add a log package to create a configuration file for the mybatis-config.xml
<? Xml version = "1.0" encoding = "UTF-8"?> 
<! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd ">
 <configuration> <! -- Enable the hump naming rule. create_time is equal to createTime --> <settings> 
<setting name = "mapUnderscoreToCamelCase" value = "true"/> </settings>
 <! -- Reference the database environment by default --> <environments default = "development"> 
<environment id = "development"> <! -- Transaction Management Method --> <transactionManager type = "JDBC"/> 
<! -- Four elements of database connection --> <dataSource type = "POOLED"> <property name = "driver" value = "com. mysql. jdbc. driver "/>
 <property name =" url "value =" jdbc: mysql: // 127.0.0.1: 3306/mybatis "/> <property name =" username "value =" root "/> 
<property name =" password "value =" root "/> </dataSource> </ environment> </environments> <! -- SQL ing file --> <mappers> 
<mapper resource = "com/dqsy/mybatis/mapper/UserMapper. xml"/> </mappers> </configuration>

5. Create a usering file UserMapper. 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">
 <mapper namespace = "com. dqsy. mybatis. mapper. UserMapper">
 <! -- Id: indicates an SQL handle, which is equivalent to statementparametaerType in JDBC: Type of the input parameter. 
In the SQL statement, the parameter resultType is accepted through the placeholder: return result type of SQL operation --> 
<! -- Single query --> <select id = "getUserById" parameterType = "java. lang. integer "resultType =" com. dqsy. mybatis. entity. user "> 
select id, name, password, age, create_time from user where id =#{ id} </select> <! -- Query list --> 
<select id = "getUserList" resultType = "com. dqsy. mybatis. entity. user "> select id, name, password, age, create_time from user </select>
 <! -- Add the user to note that the parameter passed here is a java parameter instead of a field name in the database --> 
<select id = "addUser" parameterType = "com. dqsy. mybatis. entity. user "> insert into user (name, password, age, create_time) 
values (# {name}, # {password}, # {age}, # {createTime }) </select> <! -- Delete a user --> <select id = "delUser" parameterType = "java. lang. Integer"> 
delete from user where id =#{ id} </select> <! -- Modify user data --> <select id = "uptUser" parameterType = "com. dqsy. mybatis. entity. user "> 
update user set name =#{ name}, password =#{ password}, age =#{ age }, create_time = # {createTime} where id = # {id} </select> </mapper>

6. Create a UserMapper. java interface corresponding to the ing file under the package.
package com.dqsy.mybatis.mapper;import java.util.List;
import com.dqsy.mybatis.entity.User;public interface UserMapper {
public User getUserById(int id);
public List<User> getUserList();
public void addUser(User user);
public void delUser(int i);public void uptUser(User user);}

7. Create a User object class (and implement the getset and tostring methods)
public class User {private int id;private String name;private String password;private int age;private Date createTime;
8. Create a test class MapperTest
Package com. dqsy. mybatis. test; 
import java. io. IOException; import java. io. inputStream; 
import java. util. date; import java. util. list;
 import org. apache. ibatis. io. resources; 
import org. apache. ibatis. session. sqlSession; 
import org. apache. ibatis. session. sqlSessionFactory; 
import org. apache. ibatis. session. sqlSessionFactoryBuilder; 
import org. junit. before; import org. junit. test; import com. dqsy. mybatis. entity. user; 
import com. dqsy. mybatis. mapper. userMapper; public class MapperTest {
private SqlSessionFactory sqlSessionFactory; @ Beforepublic void init () throws IOException {
String configFile = "mybatis-config.xml"; 
InputStream inputStream = Resources. getResourceAsStream (configFile);
 sqlSessionFactory = new SqlSessionFactoryBuilder (). build (inputStream) ;}
@ Testpublic void TestGetUserById () {SqlSession sqlSession = sqlSessionFactory. openSession ();
 UserMapper userMapper = sqlSession. getMapper (UserMapper. class); 
System. out. println (userMapper. getUserById (1); sqlSession. close () ;}
// query user @ Testpublic void TestGetUserList () {
SqlSession sqlSession = sqlSessionFactory. openSession ();
 UserMapper userMapper = sqlSession. getMapper (UserMapper. class); 
List <User> users = userMapper. getUserList (); 
for (User u: users) {
System. out. println (u);} sqlSession. close () ;}
// add user @ Testpublic void TestAddUser () {SqlSession sqlSession = sqlSessionFactory. openSession ();
 UserMapper userMapper = sqlSession. getMapper (UserMapper. class); User user = new User (); user. setName ("Lu jinhuan");
 user. setPassword ("123"); user. setAge (23); user. setCreateTime (new Date (); userMapper. addUser (user); sqlSession. commit (); 
sqlSession. close () ;}// delete user @ Testpublic void TestdelUser () {SqlSession sqlSession = sqlSessionFactory. openSession (); 
UserMapper userMapper = sqlSession. getMapper (UserMapper. class); userMapper. delUser (1); sqlSession. commit (); sqlSession. close () ;}
// modify user @ Testpublic void TestuptUser () {
SqlSession sqlSession = sqlSessionFactory. openSession (); 
UserMapper userMapper = sqlSession. getMapper (UserMapper. class);
 User user = new User (); user. setId (2); user. setName ("Wang Wei"); 
user. setPassword ("123"); user. setAge (23); user. setCreateTime (new Date (); 
userMapper. uptUser (user); sqlSession. commit (); sqlSession. close ();}}

8. If the test result is shown here, I just need to cut the database diagram.
Note the structure of the entire package.
Iii. Summary (differences between # {} and $ {}) # {} indicates a placeholder, and # {} receives input parameters. The types can be simple, pojo, and hashmap.
If you receive a simple type, you can enter value or another name in.
# {} Receives the value of a pojo object, reads the property value from the object through OGNL, and obtains the property value of the object through the property. Property. Property... method.

$ {} Indicates a splicing symbol, which references SQL injection. Therefore, $ {} is not recommended {}.
$ {} Receives input parameters. The type can be simple, pojo, or hashmap.
If you receive a simple type, $ {} can only be written as value.
$ {} Receives the value of a pojo object, reads the property value from the object through OGNL, and obtains the property value of the object through properties.

SelectOne and selectList
The dynamic proxy object calls sqlSession. selectOne () and sqlSession. selectList () is determined by the return value of the mapper interface method. If list is returned, the selectList method is called. If a single object is returned, the selectOne method is called.

Namespace
Mybatis officially recommends using mapper proxy to develop mapper interfaces. programmers do not need to write mapper interface implementation classes. When using mapper proxy methods, you can use pojo to wrap objects or map objects as input parameters, ensure the universality of dao.

View comments


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.