Initial Mybatis framework

Learning objectives

  • Understand the concept of data persistence and ORM principles
  • Understanding the concept of MyBatis is a bit characteristic at the first level
  • Build MyBatis environment
  • Understand the difference and relationship between MyBatis and JDBC
  • Understand the scope and declaration cycle of core classes
  • Master the structure and content of global configuration file

Frame technology

  • Is a semi-finished product of an application
  • Provide a reusable common structure
  • A group of components organized according to certain rules

Analysis advantage

  • Don't think about public issues
  • Focus on implementation at the business layer
  • Unified structure, easy to use, learn and maintain

Spring

  • Dependency injection container / AOP implementation
  • Declarative transaction
  • Simplify Java EE applications
  • Adhesive, assemble everyone together

Spring MVC

  • MVC Model2 implementation with the clearest structure
  • Highly configurable, supporting multiple view technologies
  • Customized development

MyBatis

  • Implementation of semi automated ORM
  • DAO layer
  • Dynamic SQL
  • Small, flexible and easy to learn

1 persistence and ORM

  • Persistence is the process of data transition between transient state and persistent state.
  • ORM(Object Relational Mapping)
    • When writing programs, process data in an object-oriented manner
    • When saving data, it is stored as a relational database
  • The ORM solution consists of the following four parts
    • Perform basic add, delete, modify, and query operations on persistent objects
    • Provide a query language or API for persistent objects
    • Object mapping tool
    • Provides interaction with transaction objects, checking, deferred loading, and other optimization functions

2 Introduction to mybatis

  • MyBatis, formerly IBatis, is an open source project of Apache
  • Chinese official website learning website
  • ORM framework
  • Establish a mapping relationship between entity classes and SQL statements
  • characteristic:
    • Based on SQL syntax, easy to learn
    • Be able to understand the underlying packaging process
    • SQL statements are encapsulated in configuration files to facilitate unified management and maintenance and reduce program coupling
    • Convenient program code debugging

3 development steps using MyBatis

1. First create a maven project and directly import the relevant dependencies of Maven warehouse in the pom file. If it is a web project, Download mybatis-3.5.2 jar The package can be imported into the project lib folder. (here we take maven project as an example):

mybatis 3.5.2 maven warehouse

<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>        

2.1 prepare the database connection configuration file, taking Oracle as an example (database.properties)

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:localhost:1521:orcl
username=ebuy
password=123456

2.2 prepare the console log configuration file (print errors can be output on the console) (log4j.properties)

log4j.rootLogger=DEBUG,CONSOLE
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.com.ebuy.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %d %c - %m%n

3. Write MyBatis core configuration file (MyBatis 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>
    <!--Import database connection parameters-->
    <properties resource="database.properties"/>

    <!--Priority here is higher than environments Configuration file in (it is generally not recommended to configure here)-->
    <!--<properties resource="database.properties">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </properties>-->

    <!--set up MyBatis Console output is log4j log file-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>

    <!--Set alias for entity class-->
    <typeAliases>
        <!--You can also specify an entity class and set an alias for it,type Specify a classpath for, alias Alias set for-->
        <!--When configured in this way, user Can be used in any use com.ebuy.pojo.SystemUser A place to live.-->
        <!--<typeAlias type="com.ebuy.pojo.SystemUser" alias="user"/>-->

        <!--You can also specify a package name, MyBatis All required packages are searched under the package name JavaBean,The default alias is its class name-->
        <package name="com.ebuy.pojo"/>
    </typeAliases>

    <!--The default load is Oracle database-->
    <environments default="oracle">
        <environment id="oracle">
            <!--Transaction manager, using jdbc Operation database-->
            <transactionManager type="jdbc"/>
            <!--Allow the use of database connection pools (improve efficiency)-->
            <dataSource type="POOLED">
                <!--Remember properties in oracle Load in driver string driver,d Is lowercase-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--To SystemUserMapper Add the interface configuration file to the running environment here-->
    <mappers>
        <!--<mapper resource="com/ebuy/dao/SystemUserMapper.xml"/>
        <mapper resource="com/ebuy/dao/SystemRoleMapper.xml"/>-->

        <!--Considering that there will be many entity class mapping configuration files in the future, you can directly import the package in one step-->
        <package name="com.ebuy.dao"/>
    </mappers>

</configuration>

4. Create entity class - pojo (note serialization)

  • SystemUser
    package com.ebuy.pojo;
    
    import java.io.Serializable;
    
    /**
     * User entity
     */
    public class SystemUser implements Serializable {
        /**
         * User ID
         */
        private String userinfo_uid;
        /**
         * Login name
         */
        private String userinfo_loginid;
        /**
         * full name
         */
        private String userinfo_name;
        /**
         * password
         */
        private String userinfo_password;
        /**
         * Gender
         */
        private String userinfo_sex;
        /**
         * E-mail
         */
        private String userinfo_email;
        /**
         * mobile phone
         */
        private String userinfo_mobile;
        /**
         * User status (1 normal 2 locked 3 logged off)
         */
        private int userinfo_status;
    
        @Override
        public String toString() {
            return "SystemUser{" +
                    "userinfo_uid='" + userinfo_uid + '\'' +
                    ", userinfo_loginid='" + userinfo_loginid + '\'' +
                    ", userinfo_name='" + userinfo_name + '\'' +
                    ", userinfo_password='" + userinfo_password + '\'' +
                    ", userinfo_sex='" + userinfo_sex + '\'' +
                    ", userinfo_email='" + userinfo_email + '\'' +
                    ", userinfo_mobile='" + userinfo_mobile + '\'' +
                    ", userinfo_status=" + userinfo_status +
                    '}';
        }
    
        public SystemUser() {
        }
    
        public SystemUser(String userinfo_uid, String userinfo_loginid, String userinfo_name, String userinfo_password, String userinfo_sex, String userinfo_email, String userinfo_mobile, int userinfo_status) {
            this.userinfo_uid = userinfo_uid;
            this.userinfo_loginid = userinfo_loginid;
            this.userinfo_name = userinfo_name;
            this.userinfo_password = userinfo_password;
            this.userinfo_sex = userinfo_sex;
            this.userinfo_email = userinfo_email;
            this.userinfo_mobile = userinfo_mobile;
            this.userinfo_status = userinfo_status;
        }
    
        public String getUserinfo_uid() {
            return userinfo_uid;
        }
    
        public void setUserinfo_uid(String userinfo_uid) {
            this.userinfo_uid = userinfo_uid;
        }
    
        public String getUserinfo_loginid() {
            return userinfo_loginid;
        }
    
        public void setUserinfo_loginid(String userinfo_loginid) {
            this.userinfo_loginid = userinfo_loginid;
        }
    
        public String getUserinfo_name() {
            return userinfo_name;
        }
    
        public void setUserinfo_name(String userinfo_name) {
            this.userinfo_name = userinfo_name;
        }
    
        public String getUserinfo_password() {
            return userinfo_password;
        }
    
        public void setUserinfo_password(String userinfo_password) {
            this.userinfo_password = userinfo_password;
        }
    
        public String getUserinfo_sex() {
            return userinfo_sex;
        }
    
        public void setUserinfo_sex(String userinfo_sex) {
            this.userinfo_sex = userinfo_sex;
        }
    
        public String getUserinfo_email() {
            return userinfo_email;
        }
    
        public void setUserinfo_email(String userinfo_email) {
            this.userinfo_email = userinfo_email;
        }
    
        public String getUserinfo_mobile() {
            return userinfo_mobile;
        }
    
        public void setUserinfo_mobile(String userinfo_mobile) {
            this.userinfo_mobile = userinfo_mobile;
        }
    
        public int getUserinfo_status() {
            return userinfo_status;
        }
    
        public void setUserinfo_status(int userinfo_status) {
            this.userinfo_status = userinfo_status;
        }
    }
    
  • SystemRole
    package com.ebuy.pojo;
    
    import java.io.Serializable;
    
    /**
     * Role entity
     */
    public class SystemRole implements Serializable {
        /**
         * Role ID
         */
        private String role_id;
        /**
         * Role name
         */
        private String role_name;
        /**
         * Role code
         */
        private String role_code;
        /**
         * Role description
         */
        private String role_description;
    
        @Override
        public String toString() {
            return "SystemRole{" +
                    "role_id='" + role_id + '\'' +
                    ", role_name='" + role_name + '\'' +
                    ", role_code='" + role_code + '\'' +
                    ", role_description='" + role_description + '\'' +
                    '}';
        }
    
        public SystemRole() {
        }
    
        public SystemRole(String role_id, String role_name, String role_code, String role_description) {
            this.role_id = role_id;
            this.role_name = role_name;
            this.role_code = role_code;
            this.role_description = role_description;
        }
    
        public String getRole_id() {
            return role_id;
        }
    
        public void setRole_id(String role_id) {
            this.role_id = role_id;
        }
    
        public String getRole_name() {
            return role_name;
        }
    
        public void setRole_name(String role_name) {
            this.role_name = role_name;
        }
    
        public String getRole_code() {
            return role_code;
        }
    
        public void setRole_code(String role_code) {
            this.role_code = role_code;
        }
    
        public String getRole_description() {
            return role_description;
        }
    
        public void setRole_description(String role_description) {
            this.role_description = role_description;
        }
    }
    

5.DAO layer SQL mapping file (mapper.xml)

  • SystemUserMapper.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">
    
    <!--namespace Is a namespace, which should be consistent with the path of the corresponding interface (if the interface is not created, MyBatis (automatically created when compiling internally)-->
    <mapper namespace="com.ebuy.dao.SystemUserMapper">
        <!--Query database system_userinfo Number of data records in-->
        <select id="count" resultType="int">
            select count(*) from system_userinfo
        </select>
    
        <!--query system_userinfo All data in-->
        <select id="selectUserAll" resultType="com.ebuy.pojo.SystemUser">
            select * from system_userinfo
        </select>
    </mapper>
    
  • SystemRoleMapper.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">
    
    <!--namespace Is a namespace, which should be consistent with the path of the corresponding interface (if the interface is not created, MyBatis (automatically created when compiling internally)-->
    <mapper namespace="com.ebuy.dao.SystemRoleMapper">
        <!--Query database system_role Number of data records in-->
        <select id="count" resultType="int">
            select count(*) from system_role
        </select>
    
        <!--query system_role All data in-->
        <select id="selectRoleAll" resultType="SystemRole">
            select * from system_role
        </select>
    
        <!--according to role_id Query role information(Parameter is int Type can not be written)(One parameter)-->
        <select id="getRoleById" parameterType="int" resultType="SystemRole">
            select * from system_role where role_id = #{roleId}
        </select>
    
        <!--according to role_id and role_name Query role information(In the case of multiple parameters, the annotation mapping parameter method can be used in the interface)-->
        <select id="getRoleByIdAndName" resultType="SystemRole">
            select * from system_role where role_id = #{roleId} and role_name = #{roleName}
        </select>
    
        <!--Query the role information according to some parameters in the class object(At this time, the parameter is a class object, so annotation mapping is not needed in the interface)-->
        <select id="getRoleByObject" parameterType="SystemRole" resultType="SystemRole">
            select * from system_role where role_id = #{role_id} and role_name = #{role_name}
        </select>
    
        <!--Insert role data-->
        <insert id="save" parameterType="SystemRole">
            insert into system_role(role_id,role_name,role_code,role_description) values(SEQ_SYSTEM_ROLE_ID.nextval,#{role_name},#{role_code},#{role_description})
        </insert>
    
        <!--according to roleId Delete role information-->
        <delete id="deleteByRoleId" parameterType="String">
            delete from system_role where role_id=#{role_id}
        </delete>
    
        <!--according to roleId Update role information-->
        <update id="updateByRoleId" parameterType="SystemRole">
            update system_role set role_name=#{role_name},role_code=#{role_code},
               role_description=#{role_description} where role_id=#{role_id}
        </update>
    </mapper>
    

6. Create test class

  • Steps:

    The I/O stream reads the core configuration file mybatis-conf.xml
    Create the SQLSessionFactory factory object and load the configuration file
    Create SQLSession object
    Call mapper file for data operation

  • SystemUserMapperTest
    package com.ebuy.test;
    
    import com.ebuy.dao.SystemUserMapper;
    import com.ebuy.pojo.SystemUser;
    import com.ebuy.util.MyBatisUtil;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    /**
     * @author Yisujun (CSDN: qq_52596258)
     * @date 2021-06-23 19:30:22
     */
    public class SystemUserMapperTest {
    
       @Test
       public void count() throws IOException {
    
           String resource = "mybatis-conf.xml";
           SqlSession sqlSession = null;
    
           //Read configuration file
           InputStream is = Resources.getResourceAsStream(resource);
    
           //Create sqlSessionFactory factory
           SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
    
           //Open sqlSession
           sqlSession = ssf.openSession();
    
           /**
            * The count here must be the same as mybatis con The id in the xmlf configuration file is consistent
            */
           int count = sqlSession.selectOne("com.ebuy.dao.SystemUserMapper.count");
    
           System.out.println(count);
           sqlSession.close();
    
       }
    
    
       @Test
       public void selectUserAll(){
           SqlSession sqlSession = MyBatisUtil.createSqlSession();
           List<SystemUser> systemUserList = sqlSession.selectList("com.ebuy.dao.SystemUserMapper.selectUserAll");
           for(SystemUser s:systemUserList){
               System.out.println(s);
           }
           sqlSession.close();
       }
    
  • As we have seen above, we have not created the corresponding entity class mapper mapping interface. In the method, we use the internal method of sqlSession, and load the id and path in the mapper configuration file. In fact, in the internal mechanism of MyBatis, the namespace in mapper-conf.xml file corresponds to the body class mapper mapping interface we should have created, Although we didn't create it ourselves, when compiling the source code in MyBatis, we will automatically create a matching related entity mapper temporary interface for us to realize our customized SQL functions. However, we generally don't recommend this, which is inefficient and not standardized.

7. Create the corresponding entity class mapper mapping interface

  • be careful:

    Ensure that the method name in the interface is consistent with the id in the mapper configuration file

  • SystemUser
    package com.ebuy.dao;
    
    import com.ebuy.pojo.SystemUser;
    
    import java.util.List;
    
    /**
     * User mapping interface (the method name in the interface should be consistent with the id method name in the mapper configuration file)
     * @author Yisujun (CSDN: qq_52596258)
     * @date 2021-06-24 16:00:18
     */
    public interface SystemUserMapper {
        /**
         * Total records in query user table
         * @return
         */
        int count();
    
        /**
         * Query all data in user table
         * @return
         */
        List<SystemUser> selectUserAll();
    }
    
  • SystemRole
    package com.ebuy.dao;
    
    import com.ebuy.pojo.SystemRole;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    /**
     * @author Yisujun (CSDN: qq_52596258)
     * @date 2021-06-24 16:00:06
     */
    public interface SystemRoleMapper {
        /**
         * Query the total number of records in the role table
         * @return
         */
        int count();
    
    
        /**
         * Query all records in role table
         * @return
         */
        List<SystemRole> selectRoleAll();
    
    
        /**
         * Querying role information according to roleId (one parameter)
         * @param roleId
         * @return
         */
        SystemRole getRoleById(int roleId);
    
    
        /**
         * Query role information according to roleId and roleName
         * @param roleId
         * @param roleName
         * @return
         */
        SystemRole getRoleByIdAndName(@Param("roleId") int roleId, @Param("roleName") String roleName);
    
    
        /**
         * According to some parameter information (roleId and roleName) in the class object
         * @param systemRole
         * @return
         */
        SystemRole getRoleByObject(SystemRole systemRole);
    
    
        /**
         * Insert role data
         * @param SystemRole
         * @return
         */
        int save(SystemRole SystemRole);
    
    
        /**
         * Delete information according to roleId
         * @param systemRole
         * @return
         */
        int deleteByRoleId(SystemRole systemRole);
    
    
        /**
         * Update information according to roleId
         * @param systemRole
         * @return
         */
        int updateByRoleId(SystemRole systemRole);
    }
    

8. In each method of the above test class, we need to re read the configuration file, create SQLSessionFactory factory object, and then create sqlsession. In this way, it is too cumbersome to call again every time. We can create a tool class to obtain sqlsession.

  • 	package com.ebuy.util;
    	
    	import org.apache.ibatis.io.Resources;
    	import org.apache.ibatis.session.SqlSession;
    	import org.apache.ibatis.session.SqlSessionFactory;
    	import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    	
    	import java.io.InputStream;
    	
    	
    	/**
    	 * @author Yisujun (CSDN: qq_52596258)
    	 * @date 2021-06-23 19:42:42
    	 */
    	public class MyBatisUtil {
    	
    	    private static SqlSessionFactory sqlSessionFactory = null;
    	
    	    static {
    	        String resource = "mybatis-conf.xml";
    	        InputStream is = null;
    	        try {
    	            is = Resources.getResourceAsStream(resource);
    	            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    	        }catch (Exception ex){
    	            ex.printStackTrace();
    	        }
    	    }
    	
    	    /**
    	     * Open SqlSession
    	     * @return
    	     */
    	    public static SqlSession createSqlSession(){
    	        /**
    	         * true : Represents a manual commit transaction (default), which is generally set to manual commit
    	         * false : Automatically commit transactions on behalf of
    	         */
    	        return sqlSessionFactory.openSession(true);
    	    }
    	
    	    /**
    	     * Close SqlSesison
    	     */
    	    public static void closeSqlSession(SqlSession sqlSession){
    	        if(sqlSession != null){
    	            sqlSession.close();
    	        }
    	    }
    	}
    

9. Use the tool class to update the test class

  • SystemUserMapperTest
    package com.ebuy.test;
    
    import com.ebuy.dao.SystemUserMapper;
    import com.ebuy.pojo.SystemUser;
    import com.ebuy.util.MyBatisUtil;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    /**
     * @author Yisujun (CSDN: qq_52596258)
     * @date 2021-06-23 19:30:22
     */
    public class SystemUserMapperTest {
    
        /**
         * Use the interface reference to call the methods in the mapper mapping file
         * @throws IOException
         */
        @Test
        public void count2() throws IOException {
    
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
    
            SystemUserMapper systemUserMapper = sqlSession.getMapper(SystemUserMapper.class);
            System.out.println(systemUserMapper.count());
            sqlSession.close();
    
        }
    
    
        /**
         * Use the interface reference to call the methods in the mapper mapping file
         * @throws IOException
         */
        @Test
        public void selectUserAll2(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemUserMapper systemUserMapper = sqlSession.getMapper(SystemUserMapper.class);
            List<SystemUser> systemUserList = systemUserMapper.selectUserAll();
            for(SystemUser s:systemUserList){
                System.out.println(s);
            }
        }
    }
    
  • SystemRoleMapperTest
    package com.ebuy.test;
    
    import com.ebuy.dao.SystemRoleMapper;
    import com.ebuy.pojo.SystemRole;
    import com.ebuy.util.MyBatisUtil;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    import java.io.IOException;
    import java.util.List;
    
    /**
     * @author Yisujun (CSDN: qq_52596258)
     * @date 2021-06-23 19:30:22
     */
    public class SystemRoleMapperTest {
    
    
        /**
         * Use the interface reference to call the methods in the mapper mapping file
         * @throws IOException
         */
        @Test
        public void count() throws IOException {
    
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
    
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            System.out.println(systemRoleMapper.count());
            sqlSession.close();
    
        }
    
    
        /**
         * Use the interface reference to call the methods in the mapper mapping file
         * @throws IOException
         */
        @Test
        public void selectRoleAll(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            List<SystemRole> systemRoleList = systemRoleMapper.selectRoleAll();
            for(SystemRole s:systemRoleList){
                System.out.println(s);
            }
        }
    
        @Test
        public void getRoleById(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            SystemRole systemRole = systemRoleMapper.getRoleById(1);
            System.out.println(systemRole);
        }
    
        @Test
        public void getRoleByIdAndName(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            SystemRole systemRole = systemRoleMapper.getRoleByIdAndName(1,"Super administrator");
            System.out.println(systemRole);
        }
    
    
        @Test
        public void getRoleByObject(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            SystemRole systemRole = new SystemRole();
            systemRole.setRole_id("1");
            systemRole.setRole_name("Super administrator");
    
            SystemRole systemRole2 = systemRoleMapper.getRoleByObject(systemRole);
            System.out.println(systemRole2);
        }
    
    
        @Test
        public void save(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            SystemRole systemRole = new SystemRole();
            systemRole.setRole_name("Financial administrator");
            systemRole.setRole_code("cwadmin");
            systemRole.setRole_description("Manage all financial operations");
    
            int r = systemRoleMapper.save(systemRole);
    
            /**
             * A very critical step is to update or insert data and submit it manually after executing SQL
             */
            sqlSession.commit();
            System.out.println("Successfully inserted:" + r + "Role data");
        }
    
    
        @Test
        public void deleteByRoleId(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            SystemRole systemRole = new SystemRole();
            systemRole.setRole_id("7");
    
            int r = systemRoleMapper.deleteByRoleId(systemRole);
    
            /**
             * A very critical step is to update or insert data and submit it manually after executing SQL
             */
            sqlSession.commit();
            System.out.println("Successfully deleted:" + r + "Role data");
        }
    
    
    
        @Test
        public void updateByRoleId(){
            SqlSession sqlSession = MyBatisUtil.createSqlSession();
            SystemRoleMapper systemRoleMapper = sqlSession.getMapper(SystemRoleMapper.class);
            SystemRole systemRole = new SystemRole();
            systemRole.setRole_id("7");
            systemRole.setRole_name("Financial administrator 222");
            systemRole.setRole_code("cwadmin22222");
            systemRole.setRole_description("Manage all financial operations 22222");
    
            int r = systemRoleMapper.updateByRoleId(systemRole);
    
            /**
             * A very critical step is to update or insert data and submit it manually after executing SQL
             */
            sqlSession.commit();
            System.out.println("Successfully updated:" + r + "Role data");
        }
    
    }
    

    So much first!!!

Keywords: Mybatis

Added by dcole on Sun, 23 Jan 2022 01:11:30 +0200