Complete dynamic sql with addition, deletion, modification and one-to-one multi-table joint query using annotations

Prerequisite
To summarize this article, the premise is that you must know basic SQL statements (I use MySQL) and the basic implementation of JDBC. On this basis, we can use some tags or annotations to implement multi-table joint queries on the database based on one-to-one and one-to-many relationships.

The second point is that we must consider the relationship between different tables when making a database. This relationship refers to a one-to-one and one-to-many relationship. For example, there are many students in a class but a student will not attend classes in different classes, so the class -> student is a one-to-many relationship, and the student - >Class is one-on-one.

After understanding the above two points, we can use Mybatis to implement multi-table joint query.

Annotation to implement joint query
First, we create a project based on the mybatis framework . The specific directory is as shown in the figure

 

Throughout the project, we need to complete the entity class package, Dao layer package and Mapper package to store our interfaces. I showed the entity class and Dao layer interfaces. 

Dao layer interface

 In the Dao layer interface, we need to write an interface that implements database operations such as addition, deletion, modification, and query. Then mybatis will automatically help us create implementation classes and implement these interfaces when we call these interfaces. Use comments to transmit our SQL statements. Some keywords we need to know: insert, delete, update, select. These four keywords are the most important. The above are the keywords that need to be known for single-table queries. If it is a multi-table joint query, we need to understand other keywords based on these keywords.


Then comes the test

Mapping relationship of multi-table joint query

resultType can encapsulate the query results into the pojo type, but the attribute name of the pojo class must be consistent with the field name of the queried database table.
If the fields queried by SQL are inconsistent with the property names of POJO, you need to use resultMap to match the field names and property names, perform manual configuration and encapsulation, and map the results to POJO.

resultMap
resultMap can map query results to complex types of pojos. For example, the query result mapping object includes pojos and lists to implement one-to-one queries and one-to-many queries.
First, configure the basic sql statement in the Mapper file.

<!-- Query all order data-->
    <!-- resultMap: fill in the id value of the configured resultMap tag-->

<select id="selectAll" resultMap="studentMap">
 select * from student
 </select>

Configure the resultMap tag to map different fields and attribute names

<!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
    <!-- id:设置ResultMap的id -->
     <resultMap id="studentMap" type="com.ye.bean.Student">
        <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
        <!-- property:主键在pojo中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
        <id property="id" column="id" />
 
        <!-- 定义普通属性 -->
         <association property="classInfo" 
          select="com.ye.dao.ClassInfoDao.selectByCid" column="cid"/>
    </resultMap>

The result can be encapsulated into the pojo type

Use resultMap for related query and
one-to-one query

Configure the Mapper.xml configuration file
OrderMapper.xml
first uses the id and result attributes to map the result set of the order class, and then uses association to map the result set of the associated object User.

    <resultMap id="studentMap" type="com.ye.bean.Student">
        <id property="sid" column="sid"/>
        <result property="sname" column="sname"/>
        <result property="sex" column="sex"/>
        <result property="phone" column="phone"/>
        <result property="address" column="address"/>
        <
    <!-- association :配置一对一属性 -->
    <!-- property:order里面的User属性名 -->
        <!-- javaType:属性类型 -->
   <association property="classInfo" select="com.ye.dao.ClassInfoDao.selectByCid" column="cid"/>
</resultMap>
 
<!-- 一对一关联,查询订单,订单内部包含用户属性 -->
 <select id="selectAll" resultMap="studentMap">
     select * from student
     </select>

test

 @Test
    public void selectAdd(){
        List<Student> students = student.selectAll();
        for (Student student1 : students) {
            System.out.println(student1);
        }
    }

Dynamic SQL
can dynamically splice SQL statements based on specific parameter conditions.

For example, in previous development, because they were not sure whether the query parameters existed, many people would use something like where 1 = 1 as a prefix, and then use AND to splice the parameters to be queried. In this way, even if the parameters to be queried are empty, The query can be executed correctly. If 1 = 1 is not added, then if the query parameter is empty, the SQL statement will become SELECT * FROM student where, and the SQL is illegal.

The main dynamic tags in mybatis are: if When the test condition is met, the SQL statement in the <if> tag will be spliced ​​together.

The where <where> tag will only add WHERE to the SQL statement when at least one child element returns the SQL statement, and if WHERE starts with AND or OR, it will be automatically deleted.

//模糊查询
 
<select id="seach" parameterType="student" resultMap="studentMap">
        select * from student
        <where>
            <if test="sname!=null and sname!=''">
            or sname like concat('%',#{sname},'%')
            </if>
            <if test="sex!=null and sex!=''">
            or sex like concat('%',#{sex},'%')
            </if>
            <if test="phone!=null and phone!=''">
            or phone like concat('%',#{phone},'%')
            </if>
            <if test="address!=null and address!=''">
            or address like concat('%',#{address},'%')
            </if>
        </where>
    </select>

 </select>When at least one child element returns a SQL statement, it will be added to the SQL statement SET, and if it is followed by SET ,, it will be automatically deleted.

 //修改
 
<update id="update" parameterType="student">
        update student
        <set>
            <if test="sname!=null and sname!=''">
            sname=#{sname},
            </if>
            <if test="sex!=null and sex!=''">
            sex=#{sex},
            </if>
            <if test="phone!=null and phone!=''">
            phone=#{phone},
            </if>
            <if test="address!=null and address!=''">
            address=#{address},
            </if>
        </set>
        where sid=#{sid}
    </update>

Test fuzzy queries

  @Test
    public void seach(){
        Student st=new Student();
        st.setSname("李");
        st.setAddress("郑");
        List<Student> seach = student.seach(st);
        System.out.println(seach);
    }

 result

 The key tag for one-to-many is: <association></association>. What is written in this tag is the mapping of the secondary table. Generally, for one-to-many, we need to figure out who is the main table, that is, the "one" in one-to-many. ”, such data will also be clearer.

Summarize

Mybatis's multi-table joint query is very important. Because of our customer needs, we often need to combine two tables together, such as the shopping cart system, so we need to first clarify the relationship between the tables, and then select Appropriate way to perform multi-table joint query. 
 

Guess you like

Origin blog.csdn.net/WJY898989/article/details/129674271