1. Introduction to MyBatis
MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping.
MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set.
MyBatis can use simple XML or annotations for configuration and raw mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
JDBC -> dbutils (auto-encapsulation) -> MyBatis -> Hibernate
Mybatis writes SQL in XML and then accesses the database.
2. Get started with MyBatis
2.1. Create a new Java project
Add mybatis and mysql driver jar: mybatis-3.1.1.jar, mysql-connector-java-5.1.7-bin.jar
2.2. Create a new table
create database mybatis;use mybatis;create table users(id int primary key auto_increment, name varchar(20), age int);insert into users (name, age) values('Tom',12);insert into users (name, age) values('Jack',11);2.3. Add mybatis configuration file conf.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"><configuration><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments></configuration>
2.4. Define the entity class corresponding to the table
public class User {private int id;private String name;private int age;//get,set method}2.5. Define the sql mapping file userMapper.xml that operates the users table
<?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.atguigu.mybatis_test.test1.userMapper"><select id="getUser" parameterType="int"resultType="com.atguigu.mybatis_test.test1.User">select * from users where id=#{id}</select></mapper>2.6. Register userMapper.xml file in conf.xml file
<mappers><mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/></mappers>
2.7. Writing test code: Execute defined select statements
public class Test {public static void main(String[] args) throws IOException {String resource = "conf.xml";//Load the configuration file of mybatis (it also loads the associated mapping file) Reader reader = Resources.getResourceAsReader(resource);//Build the factory of sqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);//Create a sqlSessionSqlSession session that can execute sql in the mapping file = sessionFactory.openSession();//Mapping SQL Identification String String Statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser";//Execute the query to return a unique user object sqlUser user = session.selectOne(statement, 1);System.out.println(user);}}3. Operate the CRUD of the users table
3.1.xml implementation
3.1.1. Define SQL mapping XML file:
<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User">insert into users(name, age) values(#{name}, #{age});</insert><delete id="deleteUser" parameterType="int">delete from users where id=#{id}</delete><update id="updateUser" parameterType="com.atguigu.ibatis.bean.User">update users set name=#{name},age=#{age} where id=#{id}</update><select id="selectUser" parameterType="int" resultType="com.atguigu.ibatis.bean.User">select * from users where id=#{id}</select><select id="selectAllUsers" resultType="com.atguigu.ibatis.bean.User">select * from users</select>3.1.2. Register this mapping file in config.xml
<mapper resource=" com/atguigu/ibatis/bean/userMapper.xml"/>
3.1.3. Called in dao
public User getUserById(int id) {SqlSession session = sessionFactory.openSession();User user = session.selectOne(URI+".selectUser", id);return user;}3.2. Implementation of annotations
3.2.1. Define the interface for SQL mapping
public interface UserMapper {@Insert("insert into users(name, age) values(#{name}, #{age})")public int insertUser(User user);@Delete("delete from users where id=#{id}")public int deleteUserById(int id);@Update("update users set name=#{name},age=#{age} where id=#{id}")public int updateUser(User user);@Select("select * from users where id=#{id}")public User getUserById(int id);@Select("select * from users")public List<User> getAllUser();}3.2.2. Register this mapping interface in config
<mapper/>
3.2.3. Called in dao
public User getUserById(int id) {SqlSession session = sessionFactory.openSession();UserMapper mapper = session.getMapper(UserMapper.class);User user = mappper.getUserById(id);return user;}4. Several places that can be optimized
4.1. The configuration for connecting to the database can be placed in a properties file separately.
## db.properties<br><properties resource="db.properties"/><property name="driver" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${username}" /><property name="password" value="${password}" />4.2. Define alias for entity classes and simplify references in SQL mapping XML files
<typeAliases><typeAlias type="com.atguigu.ibatis.bean.User" alias="_User"/></typeAliases>
4.3. You can add log4j configuration file under src to print log information
1. Add jar:
log4j-1.2.16.jar
2.1. log4j.properties (Method 1)
log4j.properties, log4j.rootLogger=DEBUG, Console#Consolelog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%nlog4j.logger.java.sql.ResultSet=INFOlog4j.logger.org.apache=INFOlog4j.logger.java.sql.Connection=DEBUGlog4j.logger.java.sql.Statement=DEBUGlog4j.logger.java.sql.PreparedStatement=DEBUG
2.2. log4j.xml (Method 2)
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"><appender name="STDOUT"><layout><param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SS} %m (%F:%L) /n" /></layout></appender><logger name="java.sql"><level value="debug" /></logger><logger name="org.apache.ibatis"><level value="debug" /></logger><root><level value="debug" /><appender-ref ref="STDOUT" /></root></log4j:configuration>5. Resolve conflicts between field names and entity class attribute names
5.1. Prepare tables and fields
CREATE TABLE orders(order_id INT PRIMARY KEY AUTO_INCREMENT,order_no VARCHAR(20),order_price FLOAT);INSERT INTO orders(order_no, order_price) VALUES('aaaa', 23);INSERT INTO orders(order_no, order_price) VALUES('bbbb', 33);INSERT INTO orders(order_no, order_price) VALUES('cccc', 22);5.2. Define entity classes
public class Order {private int id;private String orderNo;private float price;}5.3. Implement the query of getOrderById(id):
Method 1: Define alias in SQL statements
<select id="selectOrder" parameterType="int" resultType="_Order">select order_id id, order_no orderNo,order_price price from orders where order_id=#{id}</select>Method 2: Through <resultMap>
<select id="selectOrderResultMap" parameterType="int" resultMap="orderResultMap">select * from orders where order_id=#{id}</select><resultMap type="_Order" id="orderResultMap"><id property="id" column="order_id"/><result property="orderNo" column="order_no"/><result property="price" column="order_price"/><result property="price" column="order_price"/><resultMap>6. Implement association table query
6.1. One-to-one association
6.1.1. Propose requirements
Query class information based on class id (information with teacher)
6.1.2. Create tables and data
CREATE TABLE teacher(t_id INT PRIMARY KEY AUTO_INCREMENT,t_name VARCHAR(20));CREATE TABLE class(c_id INT PRIMARY KEY AUTO_INCREMENT,c_name VARCHAR(20),teacher_id INT);ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id); INSERT INTO teacher(t_name) VALUES('LS1');INSERT INTO teacher(t_name) VALUES('LS2');INSERT INTO class(c_name, teacher_id) VALUES('bj_a', 1);INSERT INTO class(c_name, teacher_id) VALUES('bj_b', 2);6.1.3. Define entity classes:
public class Teacher {private int id;private String name;}public class Classes {private int id;private String name;private Teacher teacher;}6.1.4. Define the sql mapping file ClassMapper.xml
<!--Method 1: Nested results: Use nested result maps to process a subset of duplicate joint results SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1--><select id="getClass3" parameterType="int" resultMap="ClassResultMap3">select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=1--><select id="getClass3" parameterType="int" resultMap="ClassResultMap3">select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#{id}</select><resultMap type="_Classes" id="ClassResultMap3"><id property="id" column="c_id"/><result property="name" column="c_id"/><association property="teacher" column="teacher_id" javaType="_Teacher"><id property="id" column="t_id"/><result property="name" column="t_name"/><result property="name" column="t_name"/></association><!-- ofType Specifies the object type in the students collection--><collection property="students" ofType="_Student"><id property="id" column="s_id"/><result property="name" column="s_name"/></collection></resultMap><!--Method 2: Nested query: Return the expected complex type by executing another SQL mapping statement SELECT * FROM class WHERE c_id=1;SELECT * FROM teacher WHERE t_id=1 //1 is the value of teacher_id obtained by the previous query SELECT * FROM student WHERE class_id=1 //1 is the value of c_id field obtained by the first query --><select id="getClass4" parameterType="int" resultMap="ClassResultMap4">select * from class where c_id=#{id}</select><resultMap type="_Classes" id="ClassResultMap4"><id property="id" column="c_id"/><result property="name" column="c_name"/><association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher2"></association><collection property="students" ofType="_Student" column="c_id" select="getStudent"></collection></resultMap><select id="getTeacher2" parameterType="int" resultType="_Teacher">SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}</select><select id="getStudent" parameterType="int" resultType="_Student">SELECT s_id id, s_name name FROM student WHERE class_id=#{id}</select>6.1.5. Test
@Testpublic void testOO() {SqlSession sqlSession = factory.openSession();Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass", 1);System.out.println(c);}@Testpublic void testOO2() {SqlSession sqlSession = factory.openSession();Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass2", 1);System.out.println(c);}6.2. One-to-many association
6.2.1. Propose requirements
Query the corresponding class information according to classId, including students and teachers
6.2.2. Create tables and data:
CREATE TABLE student(s_id INT PRIMARY KEY AUTO_INCREMENT,s_name VARCHAR(20),class_id INT);INSERT INTO student(s_name, class_id) VALUES('xs_A', 1);INSERT INTO student(s_name, class_id) VALUES('xs_B', 1);INSERT INTO student(s_name, class_id) VALUES('xs_C', 1);INSERT INTO student(s_name, class_id) VALUES('xs_D', 2);INSERT INTO student(s_name, class_id) VALUES('xs_E', 2);INSERT INTO student(s_name, class_id) VALUES('xs_F', 2);6.2.3. Define entity classes
public class Student {private int id;private String name;}public class Classes {private int id;private String name;private Teacher teacher;private List<Student> students;}6.2.4. Define the sql mapping file ClassMapper.xml
<!--Method 1: Nested results: Use nested result maps to process a subset of duplicate joint results SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1--><select id="getClass3" parameterType="int" resultMap="ClassResultMap3">select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=1--><select id="getClass3" parameterType="int" resultMap="ClassResultMap3">select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#{id}</select><resultMap type="_Classes" id="ClassResultMap3"><id property="id" column="c_id"/><result property="name" column="c_id"/><association property="teacher" column="teacher_id" javaType="_Teacher"><id property="id" column="t_id"/><result property="name" column="t_name"/><result property="name" column="t_name"/></association><!-- ofType Specifies the object type in the students collection--><collection property="students" ofType="_Student"><id property="id" column="s_id"/><result property="name" column="s_name"/></collection></resultMap><!--Method 2: Nested query: Return the expected complex type by executing another SQL mapping statement SELECT * FROM class WHERE c_id=1;SELECT * FROM teacher WHERE t_id=1 //1 is the value of teacher_id obtained by the previous query SELECT * FROM student WHERE class_id=1 //1 is the value of c_id field obtained by the first query --><select id="getClass4" parameterType="int" resultMap="ClassResultMap4">select * from class where c_id=#{id}</select><resultMap type="_Classes" id="ClassResultMap4"><id property="id" column="c_id"/><result property="name" column="c_name"/><association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher2"></association><collection property="students" ofType="_Student" column="c_id" select="getStudent"></collection></resultMap><select id="getTeacher2" parameterType="int" resultType="_Teacher">SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}</select><select id="getStudent" parameterType="int" resultType="_Student">SELECT s_id id, s_name name FROM student WHERE class_id=#{id}</select>6.2.5. Test
@Testpublic void testOM() {SqlSession sqlSession = factory.openSession();Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass3", 1);System.out.println(c);}@Testpublic void testOM2() {SqlSession sqlSession = factory.openSession();Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass4", 1);System.out.println(c);}7. Dynamic SQL and fuzzy query
7.1. Requirements
Implement multi-condition query user (name fuzzy matching, age between the specified minimum value and the maximum value).
7.2. Prepare database and tables
create table d_user( id int primary key auto_increment, name varchar(10),age int(3));insert into d_user(name,age) values('Tom',12); insert into d_user(name,age) values('Bob',13); insert into d_user(name,age) values('Jack',18);7.3.ConditionUser(query conditional entity class) private String name;private int minAge;private int maxAge;7.4.User table entity class
private int id;private String name;private int age;
7.5.userMapper.xml (map file)
<?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.atguigu.day03_mybatis.test6.userMapper"><select id="getUser" parameterType="com.atguigu.day03_mybatis.test6.ConditionUser" resultType="com.atguigu.day03_mybatis.test6.User">select * from d_user where age>=#{minAge} and age<=#{maxAge}<if test='name!="%null%"'>and name like #{name}</if></select></mapper>7.6.UserTest(test)
public class UserTest {public static void main(String[] args) throws IOException {Reader reader = Resources.getResourceAsReader("conf.xml");SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);SqlSession sqlSession = sessionFactory.openSession();String statement = "com.atguigu.day03_mybatis.test6.userMapper.getUser";List<User> list = sqlSession.selectList(statement, new ConditionUser("%a%", 1, 12));System.out.println(list);}}Dynamic SQL tags available in MyBatis
8. Calling stored procedures
8.1. Make a demand
Query the number of males or females, if the incoming is 0, females otherwise males
8.2. Prepare database tables and stored procedures:
create table p_user( id int primary key auto_increment, name varchar(10),sex char(2));insert into p_user(name,sex) values('A',"male"); insert into p_user(name,sex) values('B',"female"); insert into p_user(name,sex) values('C',"male"); #Create stored procedure (seek the number of males or females, if the incoming is 0, females are otherwise males)DELIMITER $CREATE PROCEDURE mybatis.ges_user_count(IN sex_id INT, OUT user_count INT)BEGIN IF sex_id=0 THENSELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='female' INTO user_count;ELSELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='male' INTO user_count;END IF;END$#Call stored procedure DELIMITER ;SET @user_count = 0;CALL mybatis.ges_user_count(1, @user_count);SELECT @user_count;8.3. Create the entity class of the table
public class User {private String id;private String name;private String sex;}8.4.userMapper.xml
<mapper namespace="com.atguigu.mybatis.test7.userMapper"><!--Query gets the number of men or women. If the incoming is 0, then females are otherwise males.CALL mybatis.get_user_count(1, @user_count);--><select id="getCount" statementType="CALLABLE" parameterMap="getCountMap">call mybatis.get_user_count(?,?)</select><parameterMap type="java.util.Map" id="getCountMap"><parameter property="sex_id" mode="IN" jdbcType="INTEGER"/><parameter property="user_count" mode="OUT" jdbcType="INTEGER"//</parameterMap></mapper>
8.5. Test
Map<String, Integer> paramMap = new HashMap<>();paramMap.put("sex_id", 0);session.selectOne(statement, paramMap);Integer userCount = paramMap.get("user_count");System.out.println(userCount);9. MyBatis cache
9.1. Understand mybatis cache
Just like most persistence layer frameworks, MyBatis also provides support for L1 and L2 caches.
1. Level 1 cache: HashMap local cache based on PerpetualCache, its storage scope is Session. After Session flush or close, all caches in the Session will be cleared.
2. The second-level cache is the same as the first-level cache. It also uses PerpetualCache and HashMap storage by default. The difference is that its storage scope is Mapper (Namespace), and it can customize the storage source, such as Ehcache.
3. For the cache data update mechanism, when a certain scope (first-level cache Session/second-level cache Namespaces) is performed in C/U/D operations, all caches in selects under this scope will be cleared by default.
9.2.mybatis Level 1 Cache
9.2.1. Query based on task
Query the corresponding user record object based on id.
9.2.2. Prepare database tables and data
CREATE TABLE c_user(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),age INT);INSERT INTO c_user(NAME, age) VALUES('Tom', 12);INSERT INTO c_user(NAME, age) VALUES('Jack', 11);9.2.3. Create the entity class of the table
public class User implements Serializable{private int id;private String name;private int age;9.2.4.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.atguigu.mybatis.test8.userMapper"><select id="getUser" parameterType="int" resultType="_CUser">select * from c_user where id=#{id}</select><update id="updateUser" parameterType="_CUser">update c_user setname=#{name}, age=#{age} where id=#{id}</update></mapper>9.2.5. Testing
/** Level 1 cache: That is, Session-level cache (on by default)*/@Testpublic void testCache1() {SqlSession session = MybatisUtils.getSession();String statement = "com.atguigu.mybatis.test8.userMapper.getUser";User user = session.selectOne(statement, 1);System.out.println(user);/** Level 1 cache will be used by default*//*user = session.selectOne(statement, 1);System.out.println(user);*//*1. It must be the same Session. If the session object has been closed(), it is impossible to use it *//*session = MybatisUtils.getSession();user = session.selectOne(statement, 1);System.out.println(user);*//*2. The query conditions are the same *//*user = session.selectOne(statement, 2);System.out.println(user);*//*3. Session.clearCache() has not been executed to clean the cache*//*session.clearCache();user = session.selectOne(statement, 2);System.out.println(user);*//*4. No operations that have been added, deleted and modified (these operations will clean up the cache)*//*session.update("com.atguigu.mybatis.test8.userMapper.updateUser",new User(2, "user", 23));user = session.selectOne(statement, 2);System.out.println(user);*/}9.3.MyBatis Level 2 Cache
9.3.1. Add a <cache> in userMapper.xml
<mapper namespace="com.atguigu.mybatis.test8.userMapper"><cache/>
9.3.2. Testing
/** Test Level 2 cache*/@Testpublic void testCache2() {String statement = "com.atguigu.mybatis.test8.userMapper.getUser";SqlSession session = MybatisUtils.getSession();User user = session.selectOne(statement, 1);session.commit();System.out.println("user="+user);SqlSession session2 = MybatisUtils.getSession();user = session2.selectOne(statement, 1);session.commit();System.out.println("user2="+user);}9.3.3. Supplementary Notes
1. All select statements in the mapping statement file will be cached.
2. Map all insert, update and delete statements in the statement file will refresh the cache.
3. The cache will be retried using the Least Recently Used (LRU, the least recently used) algorithm.
4. The cache will be refreshed according to the specified time interval.
5. The cache will store 1024 objects
<cacheeviction="FIFO" //The recycling strategy is first-in, first-out flushInterval="60000" //Automatic refresh time 60ssize="512" //Cache up to 512 reference objects readOnly="true"//Read only
10. Spring integration MyBatis
10.1. Add jar
【mybatis】
mybatis-3.2.0.jar
mybatis-spring-1.1.1.jar
log4j-1.2.17.jar
【spring】
spring-aop-3.2.0.RELEASE.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
spring-jdbc-3.2.0.RELEASE.jar
spring-test-3.2.4.RELEASE.jar
spring-tx-3.2.0.RELEASE.jar
aopalliance-1.0.jar
cglib-nodep-2.2.3.jar
commons-logging-1.1.1.jar
【MYSQL driver package】
mysql-connector-java-5.0.4-bin.jar
10.2. Database tables
CREATE TABLE s_user(user_id INT AUTO_INCREMENT PRIMARY KEY,user_name VARCHAR(30),user_birthday DATE,user_salary DOUBLE)
10.3. Entity Class: User
public class User {private int id;private String name;private Date birthday;private double salary;//set,get method}10.4.DAO interface: UserMapper (XXXMapper)
public interface UserMapper {void save(User user);void update(User user);void delete(int id);User findById(int id);List<User> findAll();}10.5.SQL mapping file: userMapper.xml (the same name as the interface ignores uppercase and uppercase)
<?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.atguigu.mybatis.test9.UserMapper"><resultMap type="User" id="userResult"><result column="user_id" property="id"/><result column="user_name" property="name"/><result column="user_birthday" property="birthday"/><result column="user_salary" property="salary"/><result column="user_salary" property="salary"/><resultMap><!-- Get the id after inserting data --><insert id="save" keyColumn="user_id" keyProperty="id" useGeneratedKeys="true">insert into s_user(user_name,user_birthday,user_salary)values(#{name},#{birthday},#{salary})</insert><update id="update">update s_userset user_name = #{name},user_birthday = #{birthday},user_salary = #{salary}where user_id = #{id}</update><delete id="delete">delete from s_userwhere user_id = #{id}</delete><select id="findById" resultMap="userResult">select *from s_userwhere user_id = #{id}</select><select id="findAll" resultMap="userResult">select *from s_user</select></mapper>10.6.spring configuration file: beans.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:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springfr amework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd"><!-- 1. Data source: DriverManagerDataSource --><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis"/><property name="username" value="root"/><property name="password" value="root"/></bean><!--2. Mybatis' SqlSession factory: SqlSessionFactoryBeandataSource / typeAliasesPackage--><bean id="sqlSessionFactory"><property name="dataSource" ref="dataSource"/><property name="typeAliasesPackage" value="com.atigu.spring_mybatis2.domain"/></bean><!--3. mybatis automatically scans to load Sql mapping files: MapperScannerConfigurersqlSessionFactory / basePackage--><bean><property name="basePackage" value="com.atigu.spring_mybatis2.mapper"/><property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean><!-- 4. Transaction Management: DataSourceTransactionManager --><bean id="txManager"><property name="dataSource" ref="dataSource"/></bean><!-- 5. Use declarative transaction--><tx:annotation-driven transaction-manager="txManager" /></beans>
10.7.mybatis configuration file: mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- After Spring integrates myBatis, this configuration file is basically unnecessary-><!-- Set external configuration file-><!-- Set a category name-><!-- Set database connection environment-><!-- Mapping file-></configuration>
10.8. Test
@RunWith(SpringJUnit4ClassRunner.class) //Use Springtest test framework @ContextConfiguration("/beans.xml") //Load configuration public class SMTest {@Autowired //Inject private UserMapper userMapper;@Testpublic void save() {User user = new User();user.setBirthday(new Date());user.setName("mary");user.setSalary(300);userMapper.save(user);System.out.println(user.getId());}@Testpublic void update() {User user = userMapper.findById(2);user.setSalary(2000);userMapper.update(user);}@Testpublic void delete() {userMapper.delete(3);}@Testpublic void findById() {User user = userMapper.findById(1);System.out.println(user);}@Testpublic void findAll() {List<User> users = userMapper.findAll();System.out.println(users);}}The above is the quick introduction to MyBatis (concise and simple analysis and easy to understand) introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!