SSM framework development web project series (5) Spring integration MyBatis and ssmmybatis

Source: Internet
Author: User

SSM framework development web project series (5) Spring integration MyBatis and ssmmybatis
Preface

In the previous MyBatis section, we can build a database access layer application independently based on MyBatis. However, in actual project development, our program is not that simple, layers are also more complex. In addition to the persistent layer mentioned here, there are also business logic layer, view layer, and so on. As the amount of code and complexity increase, the problems of object creation and management, and coupling between layers are also brought about. Spring is a popular framework that solves many problems, such as loose coupling between layers and help to manage objects. If you are prepared to learn about MyBatis, you should have learned more or less about Spring. In this article, we will integrate MyBatis with Spring, first, we need to have a basic understanding of the core concepts of Spring, IOC and AOP.

First, review IOC, Inversion of ControlIOC) In Spring, the coupling problem between layers is solved by control inversion. What is the control and how is the reversal? At the early stage of learning, the new statement is often used to create objects. If you need an Instance Object of the Person class, you can use Person p = new Person (); obtain what we want and further extend. In our development, if the business logic Service layer needs an instance of the persistent layer Dao, we can also directly create a Dao instance in this Service, which is equivalent to controlling the creation and management of this object. However, after Spring is introduced in the project, we do not need to create objects on our own, but instead create and manage objects by Spring. In terms of control reversal, we should control the creation and management of objects. The reversal of these responsibilities was originally our responsibility, now it is reversed to the management of Spring containers. In addition, IOC is often accompanied by the concept of DI (Dependency Injection) Dependency Injection. Why do we need to create (obtain) another class object in the class of a layer, it is because of the dependency between classes. If we create an object in the class, the project is highly coupled and the flexibility is greatly reduced. Through dependency injection, we can easily obtain the objects created and managed by the container, without the need to hard code the objects in the program to achieve decoupling. Dependency injection, based on Java reflection, is a specific implementation method for controlling inversion.

AOP (Aspect Oriented Programming) for Aspect-Oriented Programming, using the proxy mode in Java, is a supplement to object-oriented Programming, rather than competition or conflict, for example, when we look at A web Project access process, we first access module A, and then the system will record the access log, and then access module B, the system will also record the access log, from the perspective of Object-oriented thinking, from the past to the next, this is a complete process. Each process includes our access and system logging operations. However, in this case, every time we access a module, the system will record the access log, and extract and encapsulate the recorded Log action in this aspect, it can reduce the repeated code of the system, reduce the Coupling Degree between modules, and improve the operability and maintainability of the system. Common applications include transaction management, log management, and security control.

Integrate MyBatis with Spring

Since the Spring container can help us create and manage objects, here, unlike the previous independent MyBatis program, we can modify the process of getting objects in Spring mode. First, let's review the method code we used to test MyBatis separately. The example is as follows:

@ Test public void testCore () throws IOException {// directly instance SqlSessionFactoryBuilder object SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder (); // MyBatis configuration file path String path = "mybatis-config.xml "; // obtain the input stream Reader = Resources. getResourceAsReader (path); // use reader to construct sessionFactory SqlSessionFactory sessionFactory = builder. build (reader); // obtain the SqlSession object SqlSession sqlSession = sessionFactory. openSession (); // obtain the deer instance DeptMapper Mapper = sqlSession. getMapper (DeptMapper. class); Dept dept = mapper. selectById (10001); Company company = dept. getCompany (); // company List <Emp> empList = dept. getEmpList (); // set of employees: System. out. println (dept );}

The SqlSessionFactory, SqlSession, Mapper instance and other objects are all manually created by ourselves. The following body starts to use Spring integration, so we can avoid code for these objects.

MySql database environment, tool Navicat for MySQL, create a Person table as follows, and fill in several pieces of test data

Create a Maven project, which can be a common Jar project. Simply select quickstart. The project structure is as follows:

For more information about POM dependencies, see SSM framework development web project series (1) Environment setup.

Entity class Person
Package com. mmm. pojo; public class Person {private Integer id; // primary key private String name; // name private String gender; // gender private Integer age; // age private String ifIT; // whether IT is engaged in public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getGender () {return gender;} public void setGender (String gender) {this. gender = gender;} public Integer getAge () {return age;} public void setAge (Integer age) {this. age = age;} public String getIfIT () {return ifIT;} public void setIfIT (String ifIT) {this. ifIT = ifIT;} @ Override public String toString () {return "Person [id =" + id + ", name =" + name + ", gender = "+ gender +", age = "+ age +", ifIT = "+ ifIT +"] ";}}
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> <! -- The class alias can be defined here, In mapper. it is much easier to use xml files --> <typeAliases> <typeAlias alias = "psn" type = "com. mmm. pojo. person "/> </typeAliases> <! -- In the environment configuration, the Transaction Manager and data source are configured in the Spring configuration file respectively, so you can leave the original part here --> <! -- <Environments default = "envir"> <environment id = "envir"> <transactionManager type = "JDBC"> </transactionManager> <dataSource type = "POOLED"> <property name = "driver" value = "com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // 192.168.0.100: 3306/ssm? CharacterEncoding = UTF-8 "/> <property name =" username "value =" root "/> <property name =" password "value =" abc123 "/> </dataSource> </ environment> </environments> --> <! -- The mapperLocations attribute configuration in SqlSessionFactoryBean in the MyBatis configuration file is integrated in Spring to scan the SQL ing xml file. Therefore, the following mappers can be left empty here --> <! -- <Mappers> <mapper resource = "com/mmm/mapper/personMapper. xml"/> </mappers> --> </configuration>
Application-root.xml
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemaLocation = "http://www.springframework.org/schema/beans http: // Www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <! -- Introduce jdbc parameter configuration --> <context: property-placeholder location = "classpath: jdbc. properties"/> <! -- Spring automatically scans base-package for classes with annotation such as @ Component @ Service added to the specified package and instantiates it --> <context: component-scan base-package = "com. mmm "/> <! -- Configure the data source --> <bean id = "dataSource" class = "org. springframework. jdbc. datasource. driverManagerDataSource "> <property name =" driverClassName "value =" $ {jdbc. driverClassName} "/> <property name =" url "value =" $ {jdbc. url} "/> <property name =" username "value =" $ {jdbc. username} "/> <property name =" password "value =" $ {jdbc. password} "/> </bean> <! -- Integration of spring and MyBatis --> <bean id = "sqlSessionFactory" class = "org. mybatis. spring. sqlSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "/> <! -- Automatically scans mapping. xml file --> <property name = "mapperLocations" value = "classpath: com/mmm/mapper /*. xml "> </property> <property name =" configLocation "value =" classpath: mybatis-config.xml "> </property> </bean> <! -- DAO interface package name, Spring will automatically find the class under --> <bean class = "org. mybatis. spring. mapper. mapperScannerConfigurer "> <property name =" basePackage "value =" com. mmm. mapper "/> <property name =" sqlSessionFactoryBeanName "value =" sqlSessionFactory "> </property> </bean> <! -- Configure the Transaction Manager --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "> </property> </bean> <tx: annotation-driven transaction-manager = "transactionManager"/> <! -- <Bean id = "personMapper" class = "org. mybatis. spring. mapper. mapperFactoryBean "> <property name =" mapperInterface "value =" com. mmm. mapper. personMapper "/> <property name =" sqlSessionFactory "ref =" sqlSessionFactory "/> </bean> --> </beans>
Jdbc. properties
jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1:3306/ssmjdbc.username=rootjdbc.password=123456
PersonMapper. java
Package com. mmm. mapper; import java. util. list; import com. mmm. pojo. person; public interface PersonMapper {// find all Person objects List <Person> selectAll ();}
PersonMapper. 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.mmm.mapper.PersonMapper">    <resultMap type="psn" id="personResultMap">        <id column="ID" property="id" />        <result column="NAME" property="name" />        <result column="GENDER" property="gender" />        <result column="AGE" property="age" />        <result column="IF_IT" property="ifIT" />    </resultMap>        <select id="selectAll" resultMap="personResultMap">        select * from person    </select>    </mapper>

Finally, the test method does not need to create a series of objects as before. You can use the following method:

package com.mmm.test;import java.util.List;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.mmm.mapper.PersonMapper;import com.mmm.pojo.Person;public class TestSpringMbs {        @SuppressWarnings("resource")    @Test    public void test() {        ApplicationContext context = new ClassPathXmlApplicationContext("application-root.xml");        PersonMapper personMapper = (PersonMapper) context.getBean("personMapper");        List<Person> list = personMapper.selectAll();        for(Person p:list) {            System.out.println(p);        }    }    }

Finally, run the test method. You can see the following results. All records in the Person table of the database are obtained, which means the database runs successfully.

Summary

Here is a basic example of integrating MyBatis with Spring. We can have a basic understanding of the general process of integrating the ORM framework with Spring, not just MyBatis, the core steps similar to Hibernate and JPA in the Spring integration process also include the section in this article. The framework will change, but the hard requirements of some systems will not change, just like the persistent layer here. You need to access the database, whether you use MyBatis, Hibernate, or even native JDBC, the password of the database's access account is encapsulated in the data source in the framework step by step. Our update commit rollback and so on are transformed into transaction management in the framework. By clarifying these hard requirements and learning with followers, you can remember and understand them more smoothly. Instead of saying that you have learned MyBatis for a long time, and you feel that database operations are okay. Then, you suddenly change to Hibernate, And you are confused about these core concepts, it often helps us to learn new knowledge quickly.

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.