MyBatis mapping file

In a map file, the <mapper> element is the root element of the map file, and other tags are its child elements.

<?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.itheima.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
        SELECT * FROM t_customer WHERE id = #{id}
    </select>
    <select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer">
        SELECT * FROM t_customer WHERE username LIKE '%${value}%'
    </select>
    <insert id="addCustomer" parameterType="com.itheima.po.Customer">
        INSERT INTO t_customer(username,jobs,phone) VALUES (#{username}, #{jobs}, #{phone})
    </insert>
    <update id="updateCustomer" parameterType="com.itheima.po.Customer">
        UPDATE t_customer SET username='${username}', jobs='${jobs}',phone='${phone}' WHERE id=${id}
    </update>
    <delete id="deleteCustomer" parameterType="Integer">
        DELETE FROM t_customer WHERE id=#{id}
    </delete>
</mapper>

select

It is used to map query statements, read data from the database, and assemble the data to business developers.

<select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
        SELECT * FROM t_customer WHERE id = #{id}
</select>

The unique identifier in the above statement is findCustomerById, which accepts a parameter of type Integer and returns an object of type Customer.
Its common properties are as follows:

Attributes illustrate
id Indicates that the identifier in the namespace is often used in combination with the namespace. After the combination is not unique, MyBatis throws an exception
parameterType This attribute represents the fully qualified name or alias of the parameter class passed into the SQL statement. Optional attribute, because MyBatis can infer the parameters of the specific incoming statement through TypeHandler, the default value is unset (depending on the driver)
resultType The fully qualified name or alias of the class of the type returned from the SQL statement. In the case of a collection class, the returned type should be the types that the collection can contain, not the collection itself. Either resultType or resultMap can be used when returning
resultMap A named reference representing the outer resultMap, which can be returned using one of resultType or resultMap
useCache It is used to control the opening and closing of the second-level cache. Its value is a boolean type. The default value is true, which means that the query results are stored in the second-level cache.
flushCache Indicates whether the local cache and second-level cache queried before MyBatis is required after calling the SQL statement. Its value is of boolean type, and the default value is false. If set to true, the local cache and the second level cache will be emptied whenever the SQL statement is called
timeout Used to set the timeout parameter, the unit is seconds, the timeout will throw an exception
fetchSize Get the total number of records set, the default value is unset (depending on the driver)
statementType It is used to set which JDBC Statement work is used by MyBatis. Its value is STATEMENT, PREPARED (default value) or CALLABLE, corresponding to Statement, PreparedStatement and CallableStatement in JDBC respectively.
resultSetType Indicates the type of result set, its value can be set to FORWARD_ONLY, SCROLL_SENSITIVE or SCROLL_INSENSITIVE, its default value is unset (depending on the driver)

insert

It is used to map the insert statement. After the statement is executed, it returns an integer representing the number of inserted records.
In addition to the attributes that contain select, its common attributes have three other attributes:

Attributes illustrate
id Indicates that the identifier in the namespace is often used in combination with the namespace. After the combination is not unique, MyBatis throws an exception
parameterType This attribute represents the fully qualified name or alias of the parameter class passed into the SQL statement. Optional attribute, because MyBatis can infer the parameters of the specific incoming statement through TypeHandler, the default value is unset (depending on the driver)
resultType The fully qualified name or alias of the class of the type returned from the SQL statement. In the case of a collection class, the returned type should be the types that the collection can contain, not the collection itself. Either resultType or resultMap can be used when returning
resultMap A named reference representing the outer resultMap, which can be returned using one of resultType or resultMap
useCache It is used to control the opening and closing of the second-level cache. Its value is a boolean type. The default value is true, which means that the query results are stored in the second-level cache.
flushCache Indicates whether the local cache and second-level cache queried before MyBatis is required after calling the SQL statement. Its value is of boolean type, and the default value is false. If set to true, the local cache and the second level cache will be emptied whenever the SQL statement is called
timeout Used to set the timeout parameter, the unit is seconds, the timeout will throw an exception
fetchSize Get the total number of records set, the default value is unset (depending on the driver)
statementType It is used to set which JDBC Statement work is used by MyBatis. Its value is STATEMENT, PREPARED (default value) or CALLABLE, corresponding to Statement, PreparedStatement and CallableStatement in JDBC respectively.
resultSetType Indicates the type of result set, its value can be set to FORWARD_ONLY, SCROLL_SENSITIVE or SCROLL_INSENSITIVE, its default value is unset (depending on the driver)
keyProperty 此属性的作用是将插入或更新操作时将记录赋值给PO类的某个属性,通常会设置为主键对应的属性。如果时需要设置联合主键,可以在多个值之间用逗号隔开
keyColum 此属性用于设置第几列是主键,当主键列不是表中的第一列是需要设置。在需要主键联合时,值可以用逗号隔开
useGeneratedKeys 此属性会使MyBatis使用JDBC的getGeneratedKeys()方法来获取由数据库内部生产的主键,如MySQL和SQL Server等自动递增的字段,其默认值为false

实例代码如下:

<insert id="addCustomer" parameterType="com.itheima.po.Customer" keyProperty="id" useGeneratedKeys="true">
        INSERT INTO t_customer(username,jobs,phone) VALUES (#{username}, #{jobs}, #{phone})
</insert>
    @Test
    public void addCustomerTest() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Customer customer = new Customer();
        customer.setUsername("keke");
        customer.setJobs("student");
        customer.setPhone("13553423238");
        int rows = sqlSession.insert("com.itheima.mapper.CustomerMapper.addCustomer", customer);
        System.out.println(customer.getId());
        if(rows > 0) {
            System.out.println("您成功插入了"+rows+"条数据");
        }else {
            System.out.println("执行插入操作失败!!!");
        }
        sqlSession.commit();
        sqlSession.close();
    }

insert和update有一个子标签selectKey。下面用selectKey标签来实现主键自动增长,以解释他的作用:

<insert id="addCustomer" parameterType="com.itheima.po.Customer">
    <selectKey keyProperty="id" resultType="Integer" order="BEFORE">
        select if(max(id) is null, 1, max(id)+1) as new newId from t_customer
    </selectKey>
    INSERT INTO t_customer(id,username,jobs,phone) VALUES (#{id},#{username}, #{jobs}, #{phone})
</insert>

selectKey元素有keyProperty,resultType,order和statementType。order属性可以设置为BEFORE和AFTER。BEFORE的话会先执行selectKey,再执行插入语句,AFTER的话会先执行插入语句,再执行selectKey。

update和delete

update映射更新语句,执行后返回一个整数,表示更新的条数。delete映射删除语句,执行后返回一个整数,代表删除的条数。其属性基本于select相同。

sql

可以用sql标签定义一段sql语句,然后可以用include标签进行重用。
演示如下:

    <sql id="customerId">
        FROM t_customer WHERE id = #{id}
    </sql>
    <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
        SELECT * <include refid="customerId"/>
    </select>

resultMap

表示结果映射集,定义映射规则,级联的更新以及定义类型的转换等。
其元素结构如下

    <resultMap id="" type=""> 
        <constructor>  <!-- 类在实例化时,用来注入结果到构造方法中-->
            <idArg></idArg>  <!-- ID参数;标记结果作为ID -->
            <arg/>  <!-- 注入到构造方法的一个普通结果 -->
        </constructor>
        <id/>  <!-- 用来表示哪个列是主键 -->
        <result/>  <!-- 注入到字段或JavaBean属性的普通结果 -->
        <association property="" />  <!-- 用于一对一关联 -->
        <discriminator javaType="">  <!-- 使用结果值来决定哪个结果集映射 -->
            <case value=""></case>  <!-- 基于某些值的结果映射 -->
        </discriminator>
    </resultMap>

实例代码如下:

<?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.itheima.mapper.UserMapper">
    <resultMap id="resultMap" type="com.itheima.po.User">
        <id property="id" column="t_id"/>
        <result property="name" column="t_name"/>
        <result property="age" column="t_age"/>
    </resultMap>
    <select id="findAllUser" resultMap="resultMap">
        SELECT * FROM t_user
    </select>
</mapper>

写一个相应的测试方法

    @Test
    public void findAllUserTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> list = sqlSession.selectList("com.itheima.mapper.UserMapper.findAllUser");
        for (User user : list) {
            System.out.println(user);
        }
        sqlSession.close();
    }

运行结果如下:

DEBUG [main] - ==>  Preparing: SELECT * FROM t_user 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 3
User [id=1, name=lucy, age=25]
User [id=2, name=lili, age=20]
User [id=3, name=jim, age=20]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324515775&siteId=291194637