MyBatis learning summary (4): MyBatis dynamic sql <select>, <insert>, <update>, <delete> tags

1. <select> element

The <select> element is used to map the select statement of SQL. The sample code is as follows:

    <!-- 根据id查询用户   -->
    <select id="findById" parameterType="Integer" resultType="com.day1.entity.User">
        select * from t_user where id = #{id}
    </select>

 In the above sample code, the value of id is a unique identifier. It receives a parameter of type Integer and returns an object of type User. The result set is automatically mapped to the User property.

In addition to the several attributes in the above sample code, the <select> element also has some commonly used attributes, as shown in the following table:

Attribute name Depiction
id It is used in combination with the Mapper namespace and is a unique identifier for MyBatis to call
parameterType Represents the fully qualified name or alias of the parameter type passed in the SQL statement. It is an optional attribute, MyBatis can infer the parameters of the specific incoming statement
resultType The type (fully qualified name or alias) returned after the SQL statement is executed. If it is a collection type, the type of the collection element is returned, and one of resultType or resultMap can be used when returning
resultMap It is a reference to the mapping set, used together with the <resultMap> element, one of resultType or resultMap can be used when returning
flushCache It is used to set whether MyBatis is required to clear the local cache and the second-level cache previously queried after calling the SQL statement. The default value is false. If set to true, the local cache and the second-level cache will be cleared whenever the SQL statement is called.
useCache The switch to start the second-level cache, the default value is true, which means that the query results will be stored in the second-level cache
timeout
Used to set the timeout parameter, the unit is second (s), the timeout will throw an exception
fetchSize Get the total number of records setting
statementType Tell MyBatis which JDBC Statement to work with, the values ​​are STATEMENT (Statement), PREPARED (PreparedStatement), CALLABLE (CallableStatement)
resultSetType This is for the ResultSet interface of JDBC, the value can be set to FORWARD_ONLY (only allow forward access), SCROLL_SENSITIVE (two-way scrolling, but not updated in time), SCROLLJNSENSITIVE (two-way scrolling, timely update)

 However, in actual development, it may be necessary to pass multiple parameters, so how to achieve it? We can do this in two ways: using the Map interface and using JavaBean.

Method 1: Use the Map interface to pass multiple parameters.

(1) Create a database table and insert data

CREATE TABLE `t_student` (
  `username` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL
);
insert into t_student values("tom", 23 ,"陕西");
 insert into t_student values("王刚", 43,"安徽");
 insert into t_student values("张伟", 43 ,"北京");
 insert into t_student values("刘倩", 19,"北京");
 insert into t_student values("陆风", 21,"上海");
 insert into t_student values("齐菲", 56,"河北");
 insert into t_student values("王可", 56,"河南");


(2) Create the Student class

public class Student {
    private String username;
    private Integer age;
    private String address;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

(3) Create IStudentDao

public interface IStudentDao {
    List<Student> findStudent(Map<String, Object> map);
}

 (4) Create studentMapper.xml file

<?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:指定了唯一的命名空间-->
<mapper namespace="com.day1.dao.IStudentDao">
    <!--  查找年龄大于30且名字开头为张的学生  -->
    <select id="findStudent" resultType="com.day1.entity.Student">
        select * from t_student where age > #{age} and username like #{nstart};
    </select>
</mapper>

 (5) Specify the mapping configuration file in SqlMapperConfig.xml

<mapper resource="com/day1/studentMapper.xml"></mapper>

(6) Test.

    @Test
    public void testFindStudent() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Map<String, Object> map = new HashMap<>();
        map.put("age", 30);
        map.put("nstart","张%");
        List<Student> students = studentDao.findStudent(map);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

Method 2: Use JavaBean to pass multiple parameters

(1) IStudentDao add method findStudentNewWay();

List<Student> findStudentNewWay(Student student);

(2) Add query statements in studentMapper.xml.

<select id="findStudentNewWay" resultType="com.day1.entity.Student" parameterType="com.day1.entity.Student">
        select * from t_student where age > #{age} and username like #{username};
    </select>

(3) Perform a test.

    @Test
    public void testFindStudent2() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setAge(30);
        student.setUsername("张%");
        List<Student> students = studentDao.findStudentNewWay(student);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

Recommendation: If there are few parameters, it is recommended to choose Map; if there are many parameters, it is recommended to choose Java Bean.

2. <insert> element

The <insert> element is used to map the insert statement. After executing an insert statement, MyBatis will return an integer indicating the number of rows affected. Its attributes are mostly the same as those of the <select> element, with the following unique attributes:

  • keyProperty: The function of this property is to assign the return value of the insert or update operation to a certain property of the PO class, usually set to the property corresponding to the primary key. If it is a joint primary key, multiple values ​​can be separated by commas.
  • keyColumn: This property is used to set which column is the primary key. It needs to be set when the primary key column is not the first column in the table. If it is a joint primary key, multiple values ​​can be separated by commas.
  • useGeneratedKeys: This attribute will make MyBatis use the getGeneratedKeys() method of JDBC to obtain the primary keys generated internally by the database, such as auto-increment fields such as MySQL and SQL Server. The default value is false.

If you need to use the primary key to associate with other businesses in actual development, there are two ways to complete it. The first way is through the self-incrementing primary key of the database table; the second way is to use the <selectKey> element of MyBatis to customize and generate the primary key. The specific configuration example code is as follows:

    <!--  添加用户  -->
    <insert id="addUser" parameterType="com.day1.entity.User">
        <!--
        keyProperty:将查询到主键值设置到 parameterType 指定的对象的那个属性
        keyColumn:数据库中的列名
        order:SELECT LAST_INSERT_ID() 执行顺序,相对于 insert 语句来说它的执行顺序
        resultType:指定 SELECTLAST_INSERT_ID() 的结果类型
         -->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into t_user(username, password) values(#{username}, #{password});
    </insert>

When executing the above sample code, the <selectKey> element is executed first, which sets the primary key of the data table through a custom statement, and then executes the insert statement.

The keyProperty attribute of the <selectKey> element specifies which attribute of the PO class the new primary key value is returned to.

  • The order attribute can be set to BEFORE or AFTER.
  • BEFORE means to execute the <selectKey> element first and then execute the insert statement.
  • AFTER means to execute the insert statement first and then execute the <selectKey> element.

3. <update> and <delete> elements

The <update> and <delete> elements are relatively simple. Their attributes are similar to those of the <insert> element and the <select> element. They also return an integer after execution, indicating that the number of rows in the database has been affected. The configuration example code is as follows:

    <!--  删除用户  -->
    <delete id="deleteById" parameterType="int">
        delete from t_user where id = #{id}
    </delete>
    <!--  更新用户信息  -->
    <update id="updateUser" parameterType="com.day1.entity.User">
        update t_user set username =#{username}, password= #{password} where id = #{id}
    </update>

4. sql element

The sql element tag is used to define reusable SQL code fragments. When using it, you only need to use the include element tag to quote, and finally achieve the purpose of SQL statement reuse; at the same time, it can be statically (in loading parameters) parameterized, different The attribute value changes through the included instance, and is used as follows:

    <!--    建立sql片段-->
    <sql id="query_student">
        <if test="username != null and username !=''">
            and username like '%${username}%'
        </if>
    </sql>
    <!--    使用include引用sql片段-->
    <select id="findStudentList" parameterType="com.day1.entity.Student" resultType="com.day1.entity.Student">
        select * from t_student
        <where>
            <include refid="query_student"/>
        </where>
    </select>

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113816962