MyBatis -- Addition, deletion and modification of tables (annotation-based implementation)

Links to the original text: https://my.oschina.net/u/1781072/blog/542610

1. MyBatis adds/deletes/alters/checks database tables

The previous article uses XML-based approach to add/delete/modify/check database

Let's look at how annotations can be used to add/delete/modify/check database tables.

1.1 First, you need to define the interface that maps sql. The code is as follows:

package org.guus.inter;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.guus.bean.User;

/**
 * 
 * @Description: Define the interface of SQL mapping and use annotations to specify the SQL to be executed by the method
 * @author Guus
 * @date 2015 August 7th 2013
 */
public interface UserMapperInterface {

    //Use the @Insert annotation to specify 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("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();
}
1.2 Next, you need to register this interface in the mybatis-config.xml configuration file, as follows:

<?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" />
			<!-- Configure database connection information -->
			<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="2015" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<!-- register userMapper.xml Documents, userMapper.xml Be located org.guus.mapping Under this package,
		//So resource is written as org/guus/mapping/userMapper.xml - >.
		<mapper resource="org/guus/mapping/userMapper.xml" />
		<!-- register UserMapper Mapping interface-->
        <mapper class="org.guus.inter.UserMapperInterface"/>
	</mappers>

</configuration>

1.3 Let's write a test class for testing. SessionUtil used in the test class is a tool class for obtaining Session. See: MyBatis -- Addition, deletion and alteration of tables (implementation based on XML)

package org.guus.test;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.guus.bean.User;
import org.guus.inter.UserMapperInterface;
import org.guus.utils.SessionUtil;
import org.junit.Test;

/**
 * 
 * @Description: Testing MyBatis's CRID operations -- annotation-based
 * @author Guus
 * @date 2015 August 7th 2013
 */
public class TestCURD2 {

    @Test
    public void Add() throws IOException{
        SqlSession sqlSession = SessionUtil.getSqlSession(true);  //true represents automatic transaction submission
        //The implementation class object of UserMapperI interface is obtained. The implementation class object of UserMapperI interface is constructed dynamically by sqlSession.getMapper(UserMapperI.class).
        UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
        User user = new User();
        user.setName("Guus3");
        user.setAge(3);
        //Perform insert operations
        int retResult = mapper.add(user);
        //You need to close SqlSession after executing SQL with SqlSession
        sqlSession.close();
        System.out.println("Add Operational return value----> "+retResult);
    }
    
    @Test
    public void Update() throws IOException{
        SqlSession sqlSession = SessionUtil.getSqlSession(true);
        UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
        User user = new User();
        user.setId(3);
        user.setName("Guus333");
        user.setAge(4);
        //Perform modification operations
        int retResult = mapper.update(user);
        sqlSession.close();
        System.out.println("Update Operational return value----> "+retResult);
    }
    
    @Test
    public void Delete() throws IOException{
        SqlSession sqlSession = SessionUtil.getSqlSession(true);
        UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
        //Perform deletion
        int retResult = mapper.deleteById(2);
        sqlSession.close();
        System.out.println("Delete Operational return value----> "+retResult);
    }
    
    @Test
    public void GetAll() throws IOException{
        SqlSession sqlSession = SessionUtil.getSqlSession();
        UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
        //Execute the query operation and automatically encapsulate the query results into List < User > Return
        List<User> lstUsers = mapper.getAll();
        sqlSession.close();
        System.out.println("GetAll Operational return value----> "+lstUsers);
    }
}
1 4. Test results:

Reproduced in: https://my.oschina.net/u/1781072/blog/542610

Keywords: SQL Mybatis xml Apache

Added by tryin_to_learn on Thu, 03 Oct 2019 02:13:21 +0300