Previous articleMyBatis Introduction Learning Tutorial (I) - In the MyBatis Quick Start, we talked about how to use Mybatis to query the data in the users table, which is a preliminary introduction to MyBatis. Today, we will explain how to use MyBatis to perform CRUD operations on the users table. Before you go to the topic, I will add some basic knowledge about mybatis and crud.
What is 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 for result sets. MyBatis can use simple XML or annotations for configuration and original mapping to map interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
MyBatis download: https://github.com/mybatis/mybatis-3/releases
Crud means
CRUD refers to the abbreviation of the first letters of several words when performing calculation processing. It is mainly used to describe the basic operational functions of the database or persistence layer in software systems.
Going to the point, the test environment used in this article is the test environment in the previous article.
1. Use MyBatis to perform CRUD operations on tables - XML-based implementation
1. Define SQL mapping XML file
The contents of the userMapper.xml file are as follows:
<?xml version="." encoding="UTF-" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper .//EN" "http://mybatis.org/dtd/mybatis--mapper.dtd"><!-- Specify a unique namespace for this mapper. The value of the namespace is conventionally set to the package name + sql map file name, so that the value of the namespace can be guaranteed to be unique. For example, namespace="me.gacl.mapping.userMapper" is me.gacl.mapping (package name) + userMapper (userMapper.xml file removal suffix)--><mapper namespace="me.gacl.mapping.userMapper"><!-- Write a query SQL statement in the select tag, set the id attribute of the select tag to getUser, the id attribute value must be unique, and the parameterType attribute cannot be reused to indicate the parameter type used in the query. The resultType attribute indicates the result set type returned by the query resultType="me.gacl.domain.User" means encapsulating the query result into an object of the User class Return to the User class, which is the entity class corresponding to the users table--><!-- Get a user object based on the id query--><select id="getUser" parameterType="int" resultType="me.gacl.domain.User">select * from users where id=#{id}</select><!-- Create user (Create) --><insert id="addUser" parameterType="me.gacl.domain.User">insert into users(name,age) values(#{name},#{age})</insert><!-- Delete user (Remove) --><delete id="deleteUser" parameterType="int">delete from users where id=#{id}</delete><!-- Modify user (Update) --><update id="updateUser" parameterType="me.gacl.domain.User">update users set name=#{name},age=#{age} where id=#{id}</update><!-- Query all users--><select id="getAllUsers" resultType="me.gacl.domain.User">select * from users</select></mapper> The unit test class code is as follows:
package me.gacl.test;import java.util.List;import me.gacl.domain.User;import me.gacl.util.MyBatisUtil;import org.apache.ibatis.session.SqlSession;import org.junit.Test;public class TestCRUDByXmlMapper {@Testpublic void testAdd(){//SqlSession sqlSession = MyBatisUtil.getSqlSession(false);SqlSession sqlSession = MyBatisUtil.getSqlSession(true);/*** Map SQL identification string, * me.gacl.mapping.userMapper is the value of the namespace attribute of the mapper tag in the userMapper.xml file, * addUser is the id attribute value of the insert tag. Through the id attribute value of the insert tag, you can find the SQL to be executed*/String statement = "me.gacl.mapping.userMapper.addUser";//Map SQL identification string User user = new User();user.setName("User Lonely and Canglang");user.setAge();//Perform the insert operation int retResult = sqlSession.insert(statement,user);//Manually submit transactions//sqlSession.commit();// After executing SQL with SqlSession, you need to close SqlSessionsqlSession.close(); System.out.println(retResult);}@Testpublic void testUpdate(){SqlSession sqlSession = MyBatisUtil.getSqlSession(true);/*** Map SQL Identification String, * me.gacl.mapping.userMapper is the value of the namespace attribute of the mapper tag in the userMapper.xml file, * updateUser is the id attribute value of the update tag. The SQL to be executed can be found through the id attribute value of the update tag. */String statement = "me.gacl.mapping.userMapper.updateUser";//Mapping SQL ID string User user = new User();user.setId();user.setName("Lonely Canglang");user.setAge();//Execute the modification operation int retResult = sqlSession.update(statement,user);//After executing SQL using SqlSession, you need to close SqlSession.close();System.out.println(retResult);}@Testpublic void testDelete(){SqlSession sqlSession = MyBatisUtil.getSqlSession(true);/*** Map SQL Identification String, * me.gacl.mapping.userMapper is the value of the namespace attribute of the mapper tag in the userMapper.xml file, * deleteUser is the id attribute value of the delete tag. The SQL to be executed can be found through the id attribute value of the delete tag*/String statement = "me.gacl.mapping.userMapper.deleteUser";//Map SQL Identification String//Execute the delete operation int retResult = sqlSession.delete(statement,);// After executing SQL with SqlSession, you need to close SqlSessionsqlSession.close();System.out.println(retResult);}@Testpublic void testGetAll(){SqlSession sqlSession = MyBatisUtil.getSqlSession();/*** Map SQL Identification String, * me.gacl.mapping.userMapper is the value of the namespace attribute of the mapper tag in the userMapper.xml file, * getAllUsers is the id attribute value of the select tag. Through the id attribute value of the select tag, you can find the SQL to be executed*/String statement to be executed = "me.gacl.mapping.userMapper.getAllUsers";//Mapping the sql identity string//Execute query operations, and automatically encapsulate the query results into List<User> Return List<User> lstUsers = sqlSession.selectList(statement);//After using SqlSession execute SQL, you need to close SqlSessionsqlSession.close(); System.out.println(lstUsers);}} 2. Use MyBatis to perform CRUD operations on tables - annotation-based implementation
1. Define the interface for SQL mapping
The code of the UserMapperI interface is as follows:
package me.gacl.mapping;import java.util.List;import me.gacl.domain.User;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;/*** @author gacl* Define the interface for SQL mapping, specify the SQL to be executed using annotations*/public interface UserMapperI {//Use the @Insert annotations to indicate the SQL to be executed by the add method@Insert("insert into users(name, age) values(#{name}, #{age})")public int add(User user);//Use the @Delete annotation to specify the SQL to be executed by the deleteById method@Delete("delete from users where id=#{id}")public int deleteById(int id);//Use the @Update annotation to specify the SQL to be executed by the update method@Update("update users set name=#{name},age=#{age} where id=#{id}")public int update(User user);//Use the @Select annotation to specify the SQL to be executed by the getById method@Select * from users where id=#{id}")public User getById(int id);//Use the @Select annotation to specify the SQL to be executed by the getAll method@Select("select * from users")public List<User> getAll();} It should be noted that we do not need to write specific implementation class code for the UserMapperI interface. This specific implementation class is dynamically constructed by MyBatis, and we only need to use it directly.
2. Register this mapping interface in the conf.xml file
<?xml version="." encoding="UTF-"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config .//EN" "http://mybatis.org/dtd/mybatis--config.dtd"><configuration><environments default="development"><environment id="development"><transactionManager type="JDBC" /><!-- Configure database connection information--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:/mybatis" /><property name="username" value="root" /><property name="password" value="XDP" /></dataSource></environment></environments><mappers><!-- Register the userMapper.xml file. The userMapper.xml is located in the package me.gacl.mapping, so the resource is written as me/gacl/mapping/userMapper.xml--><mapper resource="me/gacl/mapping/userMapper.xml"/><!-- Register UserMapper mapping interface-><mapper//mappers></configuration>
The code of the unit test class is as follows:
package me.gacl.test;import java.util.List;import me.gacl.domain.User;import me.gacl.mapping.UserMapperI;import me.gacl.util.MyBatisUtil;import org.apache.ibatis.session.SqlSession;import org.junit.Test;public class TestCRUDByAnnotationMapper {@Testpublic void testAdd(){SqlSession sqlSession = MyBatisUtil.getSqlSession(true);//Get the implementation class object of the UserMapperI interface. The implementation class object of the UserMapperI interface is dynamically constructed by sqlSession.getMapper(UserMapperI.class). UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);User user = new User();user.setName("userxdp");user.setAge();int add = mapper.add(user);//After using SqlSession to execute SQL, you need to close SqlSessionsqlSession.close(); System.out.println(add);}@Testpublic void testUpdate(){SqlSession sqlSession = MyBatisUtil.getSqlSession(true);//Get the implementation class object of the UserMapperI interface. The implementation class object of the UserMapperI interface is dynamically constructed by sqlSession.getMapper(UserMapperI.class) UserMapperI mapper = sqlSession.getMapper(UserMapperI.class); User user = new User();user.setId();user.setName("Long Lang_xdp");user.setAge();//Execute the modification operation int retResult = mapper.update(user);//After using SqlSession, you need to close SqlSessionsqlSession.close();System.out.println(retResult);}@Testpublic void testDelete(){SqlSession sqlSession = MyBatisUtil.getSqlSession(true);//Get the implementation class object of the UserMapperI interface. The implementation class object of the UserMapperI interface is dynamically constructed by sqlSession.getMapper(UserMapperI.class) UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);//Execute the delete operation int retResult = mapper.deleteById();//After using SqlSession to execute SQL, you need to close SqlSessionsqlSession.close(); System.out.println(retResult);}@Testpublic void testGetUser(){SqlSession sqlSession = MyBatisUtil.getSqlSession();//Get the implementation class object of the UserMapperI interface. The implementation class object of the UserMapperI interface is dynamically constructed by sqlSession.getMapper(UserMapperI.class) UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);//Execute query operations and automatically encapsulate the query results into User Return User user = mapper.getById();//After using SqlSession to execute SQL, you need to close SqlSessionsqlSession.close(); System.out.println(user);}@Testpublic void testGetAll(){SqlSession sqlSession = MyBatisUtil.getSqlSession();//Get the implementation class object of the UserMapperI interface. The implementation class object of the UserMapperI interface is dynamically constructed by sqlSession.getMapper(UserMapperI.class) UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);//Execute the query operation and automatically encapsulate the query result into List<User> and return List<User> lstUsers = mappper.getAll();// After executing SQL using SqlSession, you need to close SqlSessionsqlSession.close(); System.out.println(lstUsers);}} The MyBatisUtil tool class code used is as follows:
package me.gacl.util;import java.io.InputStream;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisUtil {/*** Get SqlSessionFactory* @return SqlSessionFactory*/public static SqlSessionFactory getSqlSessionFactory() {String resource = "conf.xml";InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);return factory;}/*** Get SqlSession* @return SqlSession*/public static SqlSession getSqlSession() {return getSqlSessionFactory().openSession();}/*** Get SqlSession* @param isAutoCommit * true Indicates that the created SqlSession object will automatically commit the transaction after SQL is executed* false Indicates that the created SqlSession object will not automatically commit the transaction after SQL is executed. At this time, we need to call sqlSession.commit() manually to submit the transaction* @return SqlSession*/public static SqlSession getSqlSession(boolean isAutoCommit) {return getSqlSessionFactory().openSession(isAutoCommit);}}All the above related codes have been tested and everyone can use them with confidence!
The above is the MyBatis learning tutorial introduced to you by the editor (II) - How to use MyBatis to perform CRUD operations on the users table. 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!