Spring and mybatis integration
Integration ideas
Spring needs to manage SqlSessionFactory through a singleton.
Spring and mybatis integrate to generate proxy objects and use SqlSessionFactory to create SqlSession. (Spring and mybatis integration are automatically completed)
The mappers of the persistence layer need to be managed by spring.
Integrate the environment
Create a new java project (close to the actual developed engineering structure)
jar package:
mybatis3.2.7 jar package
spring3.2.0 jar package
Mybatis and spring integration package: Early Ibatis and spring integration was provided by spring, and now Mybatis and spring integration is provided by mybatis.
All jar packages (including springmvc)
Engineering structure
Step 1: Integrate and configure sqlSessionFactory
Configure sqlSessionFactory and data source in applicationContext.xml
sqlSessionFactory is under the integration package of mybatis and spring.
<!-- Loading the configuration file--><context:property-placeholder location="classpath:db.properties" /><!-- Data source, use dbcp --><bean id="dataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="maxActive" value="10" /><property name="maxIdle" value="5" /></bean><!-- sqlSessinFactory --><bean id="sqlSessionFactory"><!-- Load mybatis configuration file --><property name="configLocation" value="mybatis/SqlMapConfig.xml" /><!-- Data source--><property name="dataSource" ref="dataSource" /></bean>Original development (after integration with spring)
sqlmap/User.xml
Load User.xml in SqlMapconfig.xml
dao(Implement class inheritance SqlSessionDaoSupport)
Previously, the dao interface implementation class needed to inject SqlSessoinFactory and inject it through spring.
Here we use spring to declare the configuration method and configure the bean of dao:
Let UserDaoImpl implement class inherit SqlSessionDaoSupport
Configure dao
Configure the dao interface in applicationContext.xml
<!-- Original dao interface--><bean id="userDao"><property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean>
Testing procedures
source_folder/UserDaoImplTest.javapublic class UserDaoImplTest {private ApplicationContext applicationContext;//Get spring container in setUp method @Beforepublic void setUp() throws Exception {applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic void testFindUserById() throws Exception {UserDao userDao = (UserDao) applicationContext.getBean("userDao");//Call user user user = userDao.findUserById(1);System.out.println(user);}}mapper agent development
Usermapper.xml and Usermapper.java
Just copy the previous project and delete the package path.
Create proxy objects through MapperFactoryBean
Because UserMapper is not an interface type, you need to use MapperFactoryBean to generate interface type
Problem with this method:
It needs to be configured for each mapper, troublesome.
Mapper scanning via MapperScannerConfigurer (recommended)
* After configuring the mapper scan path through the basePackage property, there is no need to configure the scan path in SqlMapperConfig.xml.
The sqlSessionFactoryBeanName property is used here because if the sqlSessionFactory property is configured, the database configuration file and data source configuration will not be loaded first (db.properties)
Test code
Reverse Engineering
Mybaits requires programmers to write sql statements themselves. Mybatis official provides reverse engineering to automatically generate the required code for mybatis execution (mapper.java, mapper.xml, po..)
In actual enterprise development, a commonly used reverse engineering method: generate java code due to the table of the database.
Download reverse engineering
How to use (can use) Run reverse engineering
It is recommended to use Java program method and do not rely on development tools.
Generate code configuration files (4 places that need to be modified)
Location where PO class is generated: cn.itcast.ssm.po
The location where the mapper mapping file is generated: cn.itcast.ssm.mapper
The location of the mapper interface generated: cn.itcast.ssm.mapper
Specify database table:
<table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName="user"></table><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- Whether to remove the automatically generated comments true: Yes: false: No--><property name="suppressAllComments" value="true" /></commentGenerator><!-- Information on database connections: driver class, connection address, username, password--><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"password="mysql"></jdbcConnection><!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg"password="yycg"></jdbcConnection> --><!-- Default false, JDBC DECIMAL and NUMERIC types resolve to Integer. When true, the JDBC DECIMAL and NUMERIC types resolve to java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject: Location of the PO class generated --><javaModelGenerator targetPackage="cn.itcast.ssm.po"targetProject="./src"><!-- enableSubPackages: Whether to use schema as the suffix of the package --><property name="enableSubPackages" value="false" /><!-- Spaces before and after the value returned from the database is cleaned--><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject: Where the mapper map file is generated--><sqlMapGenerator targetPackage="cn.itcast.ssm.mapper" targetProject="./src"><!-- enableSubPackages: Whether to let schema be the suffix of the package--><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage: Location of mapper interface generation --><javaClientGenerator type="XMLMAPPER"targetPackage="cn.itcast.ssm.mapper" targetProject="./src"><!-- enableSubPackages: Whether to use schema as the suffix of the package --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- Specify database table--><table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName="user"></table></context></generatorConfiguration>
Execute the generator
Generated code
Use generated code
You need to copy the generated code in the generated project to your own project.
Testing methods in ItemsMapper
//Custom condition query @Testpublic void testSelectByExample() {ItemsExample itemsExample = new ItemsExample();//Construct query conditions through criteria ItemsExample.Criteria criteria = itemsExample.createCriteria();criteria.andNameEqualTo("Notebook 3");//May return multiple records List<Items> list = itemsMapper.selectByExample(itemsExample);System.out.println(list);}//Query @Testpublic void based on the primary key testSelectByPrimaryKey() {Items items = itemsMapper.selectByPrimaryKey(1);System.out.println(items);}//Insert @Testpublic void testInsert() {//Construct items object Items items = new Items();items.setName("Mobile");items.setPrice(999f);itemsMapper.insert(items);}//Update data @Testpublic void testUpdateByPrimaryKey() {//Update all fields, you need to query it first and then update Items items = itemsMapper.selectByPrimaryKey(1);items.setName("Water Cup");itemsMapper.updateByPrimaryKey(items);//If the incoming field is not empty, use this method in batch updates. There is no need to query first and then update //itemsMapper.updateByPrimaryKeySelective(record);}The above is a brief analysis of the integration and reverse engineering of Spring and MyBatis, which I hope 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!