mybatis primary mapping

I. Introduction

For the systematic learning knowledge, please identify the knowledge seeker (same as the public number). If you miss the author, you may have to take many detours through the first introductory article. The white people should be familiar with the construction process of mybatis. This article The main talk is how to use mybatis to implement the addition, deletion and modification of the database, as well as related label attributes and configuration instructions. It can be said that this article is a solid foundation for your future study and work. Xiaobai should read it carefully and knock it carefully. The following is the prepared SQL statement. This article is so strong that there are no friends! ! ! !

CREATE TABLE `course` (
  `courseName` varchar(255) DEFAULT NULL COMMENT '课程名称',
  `coursePrice` decimal(10,2) DEFAULT NULL COMMENT '课程价格',
  `courseId` int(11) NOT NULL AUTO_INCREMENT COMMENT '课程id',
  PRIMARY KEY (`courseId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='课程';


INSERT INTO `mybatis`.`course`(`courseName`, `coursePrice`, `courseId`) VALUES ('java基础课', 500.00, 1);
INSERT INTO `mybatis`.`course`(`courseName`, `coursePrice`, `courseId`) VALUES ('javaWeb课程', 1000.00, 2);

复制代码

Two pom.xml

The introduced dependencies are consistent with the previous article, this time we will use junit unit tests.

 <dependencies>
        <!-- mybatis support-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- log4j support -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- junit support -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- mysql support -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>

    </dependencies>
复制代码

Three log4j.properties

Log4j.properties is placed in the resource directory, modify the package name and configure the log level to debug, used to print sql;

log4j.rootLogger = info,stdout

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
## 注意改薄
log4j.logger.com.zszxz.mybatis.config.mapper = debug
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

复制代码

Four entities

Mybatis often uses entities that can be used as encapsulation parameters or to map the returned result set to entities;

/**
 * @Author lsc
 * <p> </p>
 */
public class Course {

    // 课程名称
    private String courseName;
    // 课程价格
    private double coursePrice;
    // 主键
    private Long courseId;

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public double getCoursePrice() {
        return coursePrice;
    }

    public void setCoursePrice(double coursePrice) {
        this.coursePrice = coursePrice;
    }

    public Long getCourseId() {
        return courseId;
    }

    public void setCourseId(Long courseId) {
        this.courseId = courseId;
    }
}
复制代码

Five mapper configuration

mybatis-config.xml is stored in the resource directory and is used to configure mybatis;

<?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">

<!-- mybaits配置 -->
<configuration>

    <!-- 全局环境配置-->
    <environments default="development">
        <environment id="development">
            <!-- 事物 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源 -->
            <dataSource type="POOLED">
                <!-- 数据库驱动 5.6以上版本使用com.mysql.cj.jdbc.Driver -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!-- 数据库路径 -->
                <property name="url" value="jdbc:mysql://192.168.0.105:3306/mybatis"/>
                <!-- 账号-->
                <property name="username" value="root"/>
                <!--密码 -->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 引入自定义mapper.xml 在resource 目录下 -->
    <mappers>
        <mapper resource="configMapper/CourseMapper.xml"/>
    </mappers>
</configuration>
复制代码

Six use method name query

6.1 Mapper interface and mxl

Pay attention to the relationship between the namespace and the interface, the relationship between the method name and id, and the return value is the fully qualified name of the class; the CourseMapper.xml file is placed in the configMapper under the resource directory;

CourseMapper.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.zszxz.mybatis.config.mapper.CourseMapper">

    <select id="getCourseList" resultType="com.zszxz.mybatis.config.entity.Course">
        SELECT * FROM course
    </select>
</mapper>    
复制代码

mapper interface

public interface CourseMapper {

    /* *
     * @Author lsc
     * <p> 查询课程列表</p>
     * @Param []
     * @Return java.util.List<com.zszxz.mybatis.config.entity.Course>
     */
    List<Course> getCourseList();
  
  }  
复制代码

6.2 Query test

The @before annotation here will be executed every time the test class is executed. The query test behind the list will directly list the test methods, and the methods under the @before annotation will not be repeated;

@RunWith(JUnit4.class)
public class SelectTest {

    SqlSession sqlSession = null;

    // @Before 会在执行测试类之前执行该方法
    @Before
    public void before() throws IOException {
        // 资源路径 resource目录下
        String resource = "mybatis-config.xml";
        // 配置mybatis获得输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 创建 SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //从 SqlSessionFactory 中获取 SqlSession
        sqlSession= sqlSessionFactory.openSession();
    }
    /* *
     * @Author lsc
     * <p> 查询课程列表</p>
     * @Param []
     * @Return void
     */
    @Test
    public void testSelect(){
        // 使用传入方法名查询形式
        List<Course> getCourseList = sqlSession.selectList("getCourseList");
        for (Course course : getCourseList){
            System.out.println(course.getCourseName());
        }
        sqlSession.close();
    }
}    
复制代码

6.3 Test results

==>  Preparing: SELECT * FROM course 
[DEBUG] 2019-12-05 21:02:00,238 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==> Parameters: 
[DEBUG] 2019-12-05 21:02:00,256 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
<==      Total: 2
java基础课
javaWeb课程
复制代码

Seven use the acquisition interface to query

This method is the mainstream method, you can not enter a method name every time you query, it is very unrealistic, we prefer to call the method directly in the object-oriented way to obtain the desired result;

7.1 Query test

The test results are consistent with the last time;

 @Test
    public void testSelect2(){
        // 获得mapper的形式
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        // 遍历打印课程
        for (Course course : courseMapper.getCourseList()){
            System.out.println(course.getCourseName());
        }
        sqlSession.close();
    }


复制代码

7.2 Description of select tag attributes

Attributes Explanation
id A unique identifier in the namespace, which can refer to the sql
parameterType The fully qualified name or alias of the input parameter, optional operation, not set by default.
resultType The fully qualified name or alias of the class of the expected type of return value, you can use resultType or resultMap, but not both
resultMap External result set mapping configuration, can be mapped with entity fields; resultType or resultMap can be used, but cannot be used at the same time
flushCache Set true to clear local cache and secondary cache, the default is false
useCache Set to true will cause the query result set to be saved to the secondary cache, the default is true for select
timeout The maximum number of milliseconds the driver waits before throwing an exception, which is not set by default and depends on the driver
fetchSize The driver returns rows in batches each time, which is not set by default
statementType Set STATEMENT, PREPARED or CALLABLE. Use Statement, PreparedStatement or CallableStatement respectively, the default value is PREPARED
resultSetType Set the result set type, FORWARD_ONLY, SCROLL_SENSITIVE, SCROLL_INSENSITIVE or DEFAULT (equivalent to unset) defaults to setting DEFAULT
databaseId If the database vendor identifier (databaseIdProvider) is configured, all statements without databaseId or matching the current databaseId will be loaded; if there are statements with or without, the statements without them will be ignored.
resultOrdered Used in nested query statements, set to true, the SQL execution results are nested results or grouping
resultSets In the case of multiple result sets, the result set names will be listed, separated by commas

Eight ordinary additions

8.1 Mapper interface method

    /* *
     * @Author lsc
     * <p> 普通新增</p>
     * @Param [course]
     * @Return int
     */
    int addCourse(Course course);
复制代码

8.2 mxl statement

    <insert id="addCourse" parameterType="com.zszxz.mybatis.config.entity.Course">
        INSERT INTO course ( courseName, coursePrice ) VALUES ( #{ courseName },#{ coursePrice });
    </insert>
复制代码

8.3 Test

 @Test
    public void testInsert(){

		// 创建入参实体 Course
        Course course = new Course();
        course.setCourseName("知识追寻者的心理课");
        course.setCoursePrice(10000);
        // 获得mapper
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        // 调用添加课程方法
        courseMapper.addCourse(course);
        // 事物提交
        sqlSession.commit();
        // 关闭会话
        sqlSession.close();
    }
复制代码

8.4 Execution results

It can be seen that we use # {} to achieve the native jdbc pre-compiled result in xml. Each entry is in the form of a? Placeholder, which effectively prevents SQL injection problems; $ {} is usually used to obtain the field name, table name, Instead of entering parameters, otherwise there will be a risk of SQL injection.

[DEBUG] 2019-12-05 21:58:44,193 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==>  Preparing: INSERT INTO course ( courseName, coursePrice ) VALUES ( ?,?); 
[DEBUG] 2019-12-05 21:58:44,221 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==> Parameters: 知识追寻者的心理课(String), 10000.0(Double)
[DEBUG] 2019-12-05 21:58:44,224 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
<==    Updates: 1
复制代码

Nine new ways to return to the primary key

9.1 Mapper interface method

    /* *
     * @Author lsc
     * <p> 新增数据并获得主键方式1</p>
     * @Param [course]
     * @Return int
     */
    int addCourseAndGetIdbyGen(Course course);
复制代码

9.2 mxl statement

In the <insert>label as compared to the <select>label extra three attributes.

  1. useGeneratedKeysIf true, it means that JDBC's getGeneratedKeys method is used to retrieve the primary key generated internally by the database. It is suitable for database management systems such as mysql and sqlServer with self-increasing primary keys. The default is false; it is only valid for insert and update operations.
  2. keyProperty On behalf of the primary key, mybaits will assign the primary key to this column, here we configure the entity field courseId; hope to assign to multiple columns, the default is separated by commas; the default is not set; only valid for insert and update operations.
  3. keyColumnIt needs to be set when the primary key column is not the first column in the table. If you want to use multiple generated columns, you can also set to a comma-separated list of attribute names. We must set it here, because the author puts the primary key in the third column, and the children who do not read the author's article carefully wait for the error! The default is unset; only valid for insert and update operations.
   <insert id="addCourseAndGetIdbyGen" parameterType="com.zszxz.mybatis.config.entity.Course" useGeneratedKeys="true" keyProperty="courseId" keyColumn="courseId">
        INSERT INTO course ( courseName, coursePrice ) VALUES ( #{ courseName },#{ coursePrice });
    </insert>
复制代码

9.3 Test

Xiaobai, please note here that the primary key obtained from the insertion is obtained from the Course entity attribute of our input;

    @Test
    public void testInsertGetId1(){

        Course course = new Course();
        course.setCourseName("知识追寻者的课程1");
        course.setCoursePrice(100000);
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        courseMapper.addCourseAndGetIdbyGen(course);
        //
        System.out.println("返回的课程id: "+course.getCourseId());
        sqlSession.commit();
        sqlSession.close();
    }
复制代码

9.4 Results

[DEBUG] 2019-12-05 22:17:01,788 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==>  Preparing: INSERT INTO course ( courseName, coursePrice ) VALUES ( ?,?); 
[DEBUG] 2019-12-05 22:17:01,820 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==> Parameters: 知识追寻者的课程1(String), 100000.0(Double)
[DEBUG] 2019-12-05 22:17:01,822 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
<==    Updates: 1
返回的课程id: 4
复制代码

Ten new ways to return to the primary key

10.1 Mapper interface method

    /* *
     * @Author lsc
     * <p> 新增数据并获得主键方式2</p>
     * @Param [course]
     * @Return int
     */
    int addCourseAndGetIdbyKey(Course course);
复制代码

10.2 mxl statement

As used herein, the <selectKey>tags do return to insert data primary key, used in this way in the self-energizing database management system having a primary key is also used for like oracle this does not have a primary key self-energizing database management system, and each database management system to support the <selectKey>tag The content is different, but all are similar, readers can refer to the relevant documents of the database management system to use. It should be noted that the order attribute , because the primary key self-increasing database management system such as MySQL is to obtain the primary key after the statement is inserted, it is used after; if it is a non-self-increasing primary key database management system such as Oracle, the primary key is before the statement is inserted And existence, it is necessary to set the property to before;

    <insert id="addCourseAndGetIdbyKey" parameterType="com.zszxz.mybatis.config.entity.Course">
        INSERT INTO course ( courseName, coursePrice, courseId ) VALUES ( #{ courseName },#{ coursePrice },#{ courseId });
        <selectKey resultType="long" order="AFTER" keyProperty="courseId">
            SELECT LAST_INSERT_ID();
        </selectKey>
    </insert>
复制代码

10.3 Testing

The code is very beautiful, no need for extra comments from the author.

	 @Test
    public void testInsertGetId2(){

        Course course = new Course();
        course.setCourseName("知识追寻者的课程2");
        course.setCoursePrice(100000);
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        courseMapper.addCourseAndGetIdbyGen(course);
        //
        System.out.println("返回的课程id: "+course.getCourseId());
        sqlSession.commit();
        sqlSession.close();
    }
复制代码

10.4 Execution results

[DEBUG] 2019-12-05 22:25:31,232 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==>  Preparing: INSERT INTO course ( courseName, coursePrice ) VALUES ( ?,?); 
[DEBUG] 2019-12-05 22:25:31,258 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==> Parameters: 知识追寻者的课程2(String), 100000.0(Double)
[DEBUG] 2019-12-05 22:25:31,261 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
<==    Updates: 1
返回的课程id: 5
复制代码

Eleven update operations

Update is relatively simple compared to query and insert;

11.1 Mapper interface method

    /* *
     * @Author lsc
     * <p> </p>
     * @Param [course]
     * @Return int
     */
    int updateCourse(Course course);
复制代码

11.2 mxl statement

    <update id="updateCourse" parameterType="com.zszxz.mybatis.config.entity.Course">
        UPDATE  course set courseName = #{courseName}, coursePrice = #{coursePrice}
         WHERE courseId = #{courseId}
    </update>
复制代码

11.3 Testing

    @Test
    public void testUpdate2(){

        Course course = new Course();
        course.setCourseName("知识追寻者的课程3");
        course.setCoursePrice(1000);
        course.setCourseId(5L);
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        courseMapper.updateCourse(course);
        sqlSession.commit();
        sqlSession.close();
    }
复制代码

11.4 Execution results

[DEBUG] 2019-12-05 22:38:46,093 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==>  Preparing: UPDATE course set courseName = ?, coursePrice = ? WHERE courseId = ? 
[DEBUG] 2019-12-05 22:38:46,121 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==> Parameters: 知识追寻者的课程3(String), 1000.0(Double), 5(Long)
[DEBUG] 2019-12-05 22:38:46,124 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
<==    Updates: 1
复制代码

Twelve delete operations

The delete operation is similar to the update operation, there is no skill difficulty;

12.1 Mapper interface method

    /* *
     * @Author lsc
     * <p> </p>
     * @Param []
     * @Return int
     */
    int deleteCourse(Long courseId);
复制代码

12.2 mxl statement

    <delete id="deleteCourse" parameterType="long">
        DELETE FROM course WHERE courseId = #{courseId}
    </delete>
复制代码

12.3 Test

    @Test
    public void testDelte(){

        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        courseMapper.deleteCourse(1L);
        sqlSession.commit();
        sqlSession.close();
    }
复制代码

12.4 Execution results

[DEBUG] 2019-12-05 22:39:29,926 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==>  Preparing: DELETE FROM course WHERE courseId = ? 
[DEBUG] 2019-12-05 22:39:29,952 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
==> Parameters: 1(Long)
[DEBUG] 2019-12-05 22:39:29,955 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159)
<==    Updates: 1
复制代码

Thirteen reference documents

mybatis official documentation

Guess you like

Origin juejin.im/post/5e959b356fb9a03c451bd177