Mybatis uses mapper code to integrate with Spring (1)

Source: Internet
Author: User

Mybatis uses mapper code to integrate with Spring (1)

The two ORM frameworks named javasselink and Hibernate, which have been used in previous java projects, are now implemented using Mybatis. Of course they have their own advantages and disadvantages. Sometimes, two frameworks can be used together in a project. In a project, technical selection is very important. Mybatis is a persistent layer framework and is a top-level project under apache. mybatis enables the program to focus mainly on SQL and generate it flexibly using the ing method provided by mybatis.

Mybatis mainly relies on SQL statements to achieve database persistence, which is a hard nut to crack in mybatis. Of course, it is also implemented by SQL statements, which is flexible but difficult to maintain.

I drew a simple mind map and explained it as follows:


Mybatis framework:

Let's talk about a Mybatis framework. Of course, we can use diagrams to illustrate it. We should try not to use text:



Description of the figure: In the early stage of the database connection, it will be created as long as it is used. It is not applicable to immediate release. The database is frequently accessed and closed, resulting in a waste of database resources, affects the database performance. Therefore, we need to use the database connection pool to manage the database connection. Here we need to use sqlSessionFactory to manage sessions. In addition, the SQL statement is hardcoded into the java code. If the SQL statement is modified, the java code needs to be re-compiled, which is not conducive to system maintenance, here we use the SQL statement configuration in the xml configuration file. Even if the SQL statement changes, you do not need to compile the java code. In addition, we should set the parameters in proparedStatement, and place the positions of the richest players in the battle space and the parameters in the xml file. In addition, we always facilitate the result set data from the resultSet, which is not conducive to system maintenance. Therefore, we automatically map the query result set to a java object.


Simple process:

Due to limited space, we mentioned it directly in the Spring integration project.

Integration with spring:

Here we use the Mapper proxy form. We put all our Mybatis mapper proxies in SqlSessionFactory for management. In addition, we will marry SqlSessionFactory to the Spring container for management. Specifically: Use SqlSessionFactoryBuilder to create a session factory SqlSessionFactory and use SqlSessionFactoryBuilder as a tool class. You do not need to use a singleton to manage SqlSessionFactoryBuilder. To create SqlSessionFactory, you only need to create a new SqlSessionFactoryBuilder. Create a sqlSession using SqlSessionFactory, manage SqlSessionFactory in standalone mode, and hand it over to Spring for management.

The integration idea is that spring needs to manage SqlSessionFactory by means of Singleton. spring and mybatis are integrated to generate proxy objects and use SQLSessionFactory to create SqlSession. (Spring and mybatis are automatically integrated) The er of the persistent layer needs to be managed by spring.

Integrated code:

1. jar package


2. Create a configuration file

First, let's look at our directory structure:


Configure SqlMapConfig. xml in mybatis

Db. properties file:

Jdbc. driver = com. mysql. jdbc. Driver
Jdbc. url = jdbc: mysql: // localhost: 3306/mybatis
Jdbc. username = root
Jdbc. password = root

Add the log4j. properties file:


# Global logging configuration#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216errorlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

The sqlmap folder is not used for the moment. It is used only when dao is directly injected into SqlSessionFactory. Here we use to directly add xml files in mapper.


Below is the most important spring applicationContext. xml file. We inject SqlSession under this file.

The configuration file is created as follows:




In the src file, we now create java cashes for our pojo and er proxies.

Let's first look at the src file directory:


User class:


Package cn. itcast. ssm. po; import java. io. serializable; import java. util. date; import java. util. list; public class User implements Serializable {// private int id corresponding to the attribute name and database table field; private String username; // User name private String sex; // gender private Date birthday; // birthday private String address; // address // private List of orders created by the user
OrdersList; public int getId () {return id;} public void setId (int id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getSex () {return sex;} public void setSex (String sex) {this. sex = sex;} public Date getBirthday () {return birthday;} public void setBirthday (Date birthday) {this. birthday = birthday;} public String getAddress () {return address;} public void setAddress (String address) {this. address = address ;}@ Overridepublic String toString () {return "User [id =" + id + ", username =" + username + ", sex =" + sex + ", birthday = "+ birthday +", address = "+ address +"] ";} public List
GetOrdersList () {return ordersList;} public void setOrdersList (List
OrdersList) {this. ordersList = ordersList ;}}

Order class:


Package com. tgb. NCREs. po; import java. util. date; import java. util. list; public class Orders {private Integer id; private Integer userId; private String number; private Date createtime; private String note; // User information private user User; // order details private List
Orderdetails; public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public Integer getUserId () {return userId;} public void setUserId (Integer userId) {this. userId = userId;} public String getNumber () {return number;} public void setNumber (String number) {this. number = null? Null: number. trim ();} public Date getCreatetime () {return createtime;} public void setCreatetime (Date createtime) {this. createtime = createtime;} public String getNote () {return note;} public void setNote (String note) {this. note = null? Null: note. trim ();} public User getUser () {return user;} public void setUser (User user) {this. user = User;} public List
GetOrderdetails () {return orderdetails;} public void setOrderdetails (List
Orderdetails) {this. orderdetails = orderdetails ;}}

Orderdetail class:




Package com. tgb. NRE. po; public class Orderdetail {private Integer id; private Integer ordersId; private Integer itemsId; private Integer itemsNum; // The commodity information corresponding to the details ?? Private Items items; public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public Integer getOrdersId () {return ordersId;} public void setOrdersId (Integer ordersId) {this. ordersId = ordersId;} public Integer getItemsId () {return itemsId;} public void setItemsId (Integer itemsId) {this. itemsId = itemsId;} public Integer getItemsNum () {return itemsNum;} public void setItemsNum (Integer itemsNum) {this. itemsNum = itemsNum;} public Items getItems () {return items;} public void setItems (Items items) {this. items = items ;}@ Overridepublic String toString () {return "Orderdetail [id =" + id + ", ordersId =" + ordersId + ", itemsId =" + itemsId + ", itemsNum = "+ itemsNum +"] ";}}

Items class:


package com.tgb.ncre.po;import java.util.Date;public class Items {    private Integer id;    private String name;    private Float price;    private String pic;    private Date createtime;    private String detail;    public Integer getId() {        return id;    }    public void setId(Integer id) { = id;    }    public String getName() {        return name;    }    public void setName(String name) { = name == null ? null : name.trim();    }    public Float getPrice() {        return price;    }    public void setPrice(Float price) {        this.price = price;    }    public String getPic() {        return pic;    }    public void setPic(String pic) {        this.pic = pic == null ? null : pic.trim();    }    public Date getCreatetime() {        return createtime;    }    public void setCreatetime(Date createtime) {        this.createtime = createtime;    }    public String getDetail() {        return detail;    }    public void setDetail(String detail) {        this.detail = detail == null ? null : detail.trim();    }}

Then, let's look at com. tgb. NRE. mapper:



Usermapper. java



Package com. tgb. NCREs. mapper; import static org. junit. assert. *; import com. tgb. NCREs. po. user; public interface UserMapper {// query User information by id public User findUserById (int id) throws Exception ;}

UserMapper. xml:


  SELECT * FROM USER WHERE id=#{value}

Note: You must ensure that the java class and xml name in the two ER er packages must be the same. Otherwise, you cannot scan all the files when creating SqlSession in applicationContext. xml.


Now let's test:

Right-click UserMapper. java and select "New" -- "Others ":




Then, we write the code:


package com.tgb.ncre.mapper;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import;import com.tgb.ncre.po.User;public class UserMapperTest {private ApplicationContext applicationContext;@Beforepublic void setUp() throws Exception {applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic void testFindUserById() throws Exception {UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");User user = userMapper.findUserById(1);System.out.println(user);}}

OK. Run JunitTest:




When studying the persistence layer framework, we need to consider multiple aspects. When we learn Mybatis, we need to consider whether there are other ORM frameworks for comparison. In this way, we can make a good selection of technology. In addition, when learning Mybatis, we also need to think about how to optimize it step by step.


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: 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.