Mybatis learning notes-02 (in update)

Article directory

1. Add operation

1.1 add insertUser() method in UserMapper interface

public interface UserMapper {
     * Query all users
     * @return
    List<User> listAllUsers();

     * Add user
     * @param user
     * @return 1 for success, 0 for failure
    int insertUser(User user);

1.2 configure add operation in Mapper mapping file UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="cn.ykf.mapper.UserMapper">
    <!-- Configure query all users -->
    <select id="listAllUsers" resultType="cn.ykf.pojo.User">
        SELECT * FROM user
    <!-- Add user -->
    <insert id="insertUser" parameterType="cn.ykf.pojo.User">
        INSERT INTO user(username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})
  • Reminder
    • When writing a mapping file, you can first write a SQL statement that can run normally on the MySQL client, then move it to the mapping file, and replace the original actual parameters with the parameter symbols of Mybatis
  • parameterType represents the fully qualified name or alias of the parameter class that will be passed into the statement.
  • The parameter symbols {username}, {birthday}, {birthday}, {sex}, and {address} must correspond to each attribute name of the User class one by one, and cannot be scribbled.
    • The property name is the XX part of getXxx()/setXxx(), which is the member variable name in most cases, but not the member variable name in a few cases, that is to say, the member variable and the property cannot be the same.
  • For descriptions of configuration files, you can view the official website documents: XML Mapping file for Mybatis

1.3 test add operation

public class MybatisTest {

    private InputStream is;
    private SqlSession sqlSession;
    private UserMapper mapper;

     * Execute before test, for initialization
    public void init() throws Exception {
        // 1. Read configuration file
        is = Resources.getResourceAsStream("mybatis-config.xml");
        // 2. Create SqlSessionFactory factory
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory =;
        // 3. Get SqlSession object
        sqlSession = factory.openSession();
        // 4. Use SqlSession to create Mapper's proxy object
        mapper = sqlSession.getMapper(UserMapper.class);

     * End of test execution for commit transactions and release resources
    public void destory() throws Exception {
        // 6. Submission
        // 7. Release resources

     * Test add user
    public void testInsertUser() {
        User user = new User();
        user.setUsername("Fish meal");
        user.setBirthday(new Date());

        // Call mapper to finish adding
        int count = mapper.insertUser(user);
        System.out.println("Add the number of : " + count);
  • It should be noted that if the transaction is not committed through sqlSession.commit(); in the destory() method, the added record will not be written to the database.
  • Because we did not set the transaction auto commit when we called openSession(), the final transaction will automatically roll back, resulting in the record not being written to the database. See below
  • The overload method of openSession() is shown in the figure below. Therefore, if you need to automatically commit a transaction, you only need factory.openSession(true); to do so.

1.4 test results

2. Delete

2.1 add the deleteUserById() method in the UserMapper interface

 * Delete user by id
 * @param userId
 * @return 1 for success, 0 for failure
int deleteUserById(Integer userId);

2.2 configure deletion in Mapper mapping file UserMapper.xml

<!-- delete user -->
<delete id="deleteUserById" parameterType="java.lang.Integer">
    DELETE FROM user WHERE id = #{uid}
  • Here are two points to pay attention to!
  • First, if the parameter is a wrapper class of basic type or basic type, and there is only one parameter, the parameter symbol can be written at will. That is, although the method in the Mapper interface is declared as int deleteUserById(Integer userId), you can write {userId} or {aaaa} in the mapping file.
  • Second, parameterType can write int, int, integer, integer and java.lang.Integer.

2.3 test deletion

 * Test delete user
public void testDeleteUserById(){
    // The id passed here is the id value existing in your database
    int count = mapper.deleteUserById(50);
    System.out.println("The number of deleted items is: " + count);

2.4 test results

3. Modify

3.1 add the updateUser method in the UserMapper interface

 * Modify user
 * @param user
 * @return 1 for success, 0 for failure
int updateUser(User user);

3.2 configure modification in Mapper mapping file UserMapper.xml

<!-- Modify user -->
<update id="updateUser" parameterType="cn.ykf.pojo.User">
    UPDATE user SET username = #{username}, birthday = #{birthday}, sex = #{sex}, address = #{address} WHERE id = #{id}

3.3 test modification

 * Test modify user
public void testUpdateUser() {
    // Because the user has not been queried according to the id, the simulation data
    User user = new User();
    user.setBirthday(new Date());
    // id is the value existing in its own database

    // Execution modification
    int count = mapper.updateUser(user);
    System.out.println("The number of modifications is: " + count);

3.4 test results

Published 4 original articles, won praise 2, visited 104
Private letter follow

Keywords: xml Mybatis Database Java

Added by matchu on Wed, 29 Jan 2020 06:37:13 +0200