MyBatis-Spring Project
Currently, most Java Internet projects are built using Spring MVC + Spring + MyBatis.
Using Spring IoC can effectively manage various Java resources and achieve the plug-and-play function; through the Spring AOP framework, database transactions can be entrusted to Spring management, eliminating a large part of the transaction code, and combining with the high flexibility, configurable, and optimized SQL characteristics of MyBatis, it is possible to build high-performance large websites.
There is no doubt that the two major frameworks, MyBatis and Spring, have become the mainstream framework combination of Java Internet technology. They have withstood the test of large data volume and large-scale requests and have been widely used in Internet systems. Using MyBatis-Spring makes the business layer and model layer better separated. At the same time, using MyBatis in the Spring environment is simpler, saving a lot of code, and you can even avoid using objects such as SqlSessionFactory and SqlSession, because MyBatis-Spring encapsulates them for us.
Excerpted from: "Java EE Internet Lightweight Framework Integrated Development"
Step 1: Create a test project
The first step is to create a new WebProject project called [MybatisAndSpring] in IDEA:
Then create 4 empty packages in [src]:
Then create a new source folder [config] to place various resource configuration files:
Then create a new [WEB-INF] default security folder under the [web] folder, and create a [classes] and [lib] under it, and change the output location of the project under [classes]:
The complete initial structure of the project is as follows:
Step 2: Introducing dependency jar package
The second step is to prepare the project's dependency jar package:
Place the jar package listed above in the [lib] folder under the [WEB-INF] folder, and then add dependencies.
Step 3: Write Spring Configuration Files
The third step is to write Spring configuration file:
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Loading configuration file --> <context:property-placeholder location="classpath:db.properties"/> <!-- Configure data source --> <bean id="dataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory"> <!-- Load MyBatis configuration file --> <property name="configLocation" value="mybatis/SqlMapConfig.xml"/> <!-- Data source--> <property name="dataSource" ref="dataSource"/> </bean></beans>Step 4: Write MyBatis configuration file
Step 4: Write the global configuration file of MyBatis under the [mybatis] package SqlMapConfig.xml:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><config> <!-- settings --> <settings> <!-- turn on the delayed loading switch--> <setting name="lazyLoadingEnabled" value="true"/> <!-- Change active loading to passive loading (i.e. loading on demand) --> <setting name="aggressiveLazyLoading" value="false"/> <!-- Turn on the global cache switch (secondary cache) default value is true --> <setting name="cacheEnabled" value="true"/> </settings> <!-- Aliases definition--> <typeAliases> <package name="cn.wmyskxz.pojo"/> </typeAliases> <!-- Load the map file--> <mappers> <!-- Load one map file at a time through the resource method--> <mapper resource="sqlmap/UserMapper.xml"/> <!-- Batch load mapper --> <package name="cn.wmyskxz.mapper"/> </mappers></configuration>
In this configuration file:
Step 5: Write Mapper and other configuration files
Step 5: Write the Mapper mapping file. Here, the name of the Mapper mapping file is still defined as "UserMapper.xml" (which is consistent with the configuration in SqlMapConfig.xml). In order to test the effect, only one query class SQL map is configured:
<?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="test"> <select id="findUserById" parameterType="_int" resultType="user"> SELECT * FROM USER WHERE id = #{id}</select></mapper>In this configuration, the output parameters are mapped to "user", because the entity class under the "cn.wmyskxz.pojo" package was configured in SqlMapConfig.xml before using alias (that is, the class name with lowercase initials), so here you just need to create the Java entity class User corresponding to "finduserById" under the "cn.wmyskxz.pojo" package:
package cn.wmyskxz.pojo;import java.io.Serializable;public class User implements Serializable { private int id; private String username; /* getter and setter */}Implementing the Serializable interface is to prepare for the subsequent use of the Mapper dynamic proxy, and there is no dynamic proxy used here.
The database connection information is configured in the database resource "db.properties" and configured in the form of "key=value". String uses "${}" to obtain the value corresponding to the key:
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8jdbc.username=rootjdbc.password=root
In addition, the log configuration is the same as the previous configuration, so I directly pasted it:
# Global logging configuration# In the development environment, the log level should be set to DEBUG, and the production environment should be set to INFO or ERRORlog4j.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
Step 6: Write the DAO layer
Step 6: Write the Data Access Object layer.
Since this project only queries the User user, there is only one class in the DAO layer. The interface interface of the DAO layer is created under the "cn.wmyskxz" package, which defines the findUserById method and the parameter is the user's id value (int type):
package cn.wmyskxz.dao;import cn.wmyskxz.pojo.User;public interface UserDAO { // Query user information based on id public User findUserById(int id) throws Exception;}Then create the UserDAO interface implementation class UserDAOImpl under the same package:
package cn.wmyskxz.dao;import cn.wmyskxz.pojo.User;import org.apache.ibatis.session.SqlSession;import org.mybatis.spring.support.SqlSessionDaoSupport;public class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO { @Override public User findUserById(int id) throws Exception { // Inherit the SqlSessionDaoSupport class and pass this.getSqlSession() Get sqlSession SqlSession sqlSession = this.getSqlSession(); User user = sqlSession.selectOne("test.findUserById", id); return user; }}There are a few explanations:
<!-- Original DAO interface--><bean id="userDAO"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean>
Note: After the DAO implementation class inherits the SqlSessionDaoSupport parent class, there is no need to define the method to obtain the SqlSession session instance class by itself. The parent class will load the data source information by default and provide a method to obtain the SqlSession class.
Step 7: Write Service Test Class
Create the [UserServiceTest] test class under the "cn.wmyskxz.test" package:
package cn.wmyskxz.test;import cn.wmyskxz.dao.UserDAO;import cn.wmyskxz.pojo.User;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UserServiceTest { private ApplicationContext applicationContext; // Get the Spring configuration file object first before executing the test method // Annotation @Before calls this method before executing all test methods of this class @Before public void setup() throws Exception { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); } @Test public void testFindUserById() throws Exception { // Get userDAO object by configuring resource objects UserDAO userDAO = (UserDAO) applicationContext.getBean("userDAO"); // Call User user user = userDAO.findUserById(1); // Output user information System.out.println(user.getId() + ":" + user.getUsername()); }}Run the test method and the output results are as follows:
Dynamic proxy + annotation implementation
The above example program is not completed using Mapper dynamic proxy and annotations. Let’s try how to use dynamic proxy and annotations:
Step 1: Write UserQueryMapper
Create a new [UserQueryMapper] proxy interface under [mapper] and use annotations:
package cn.wmyskxz.mapper;import cn.wmyskxz.pojo.User;import org.apache.ibatis.annotations.Select;public interface UserQueryMapper { @Select("SELECT * FROM USER WHERE id = #{id}") public User findUserById(int id) throws Exception;}Note: By default, the bean's name is userQueryMapper (i.e., the first letter is lowercase)
Now that we have the proxy class, we need to notify Spring to scan this class here. Mapper needs to use a special scanner to scan the configuration object:
<!-- Mapper Scanner--><bean> <!-- Scan the components under the cn.wmyskxz.mapper package--> <property name="basePackage" value="cn.wmyskxz.mapper"/></bean>
Step 2: Write a test class
This time we are no longer fetching the userDAO object, but the defined Mapper proxy object userQueryMapper:
package cn.wmyskxz.test;import cn.wmyskxz.mapper.UserQueryMapper;import cn.wmyskxz.pojo.User;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UserServiceTest { private ApplicationContext applicationContext; // Get the Spring configuration file object first before executing the test method // Annotation @Before calls this method before executing all test methods of this class @Before public void setup() throws Exception { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); } @Test public void testFindUserById() throws Exception { // Get userDAO object by configuring resource objects UserQueryMapper userQueryMapper = (UserQueryMapper) applicationContext.getBean("userQueryMapper"); // Call UserDAO method User user = userQueryMapper.findUserById(1); // Output user information System.out.println(user.getId() + ":" + user.getUsername()); }}Run the test method and get the correct result:
You can see that the query results are the same as those of previous non-Mapper agents.
Summarize
The above is the perfect integration method between MyBatis and Spring introduced to you by the editor. I hope it 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!