search
HomeJavajavaTutorialExample tutorial of sql mapping file

Example tutorial of sql mapping file

Jul 17, 2017 pm 03:15 PM
documentmapping

Sql Mapping File

MyBatis The real power is in the mapping statement. Comparing the price with jdbc with equivalent functions, mapping files save a lot of code. MyBatis is built to focus on SQL.

The sql mapping file has the following top-level elements: (in order)

cache configures the cache for a given namespace.

cache-ref references cache configuration from other namespaces.

resultMap The most complex and powerful element, used to describe how to load your objects from the database result set.

parameterMap has been deprecated! Old-school style parameter mapping. Inline parameters are preferred, this element may be removed in the future.

SQL block can be reused and can also be referenced by other statements.

insert mapping insert statement.

update mapping update statement.

delete mapping delete statement.

select mapping query statement.

MyBatis is built to focus on SQL, keeping it away from ordinary methods.

SQL mapping files have a few top-level elements (in the order they should be defined):

>mapper: The root element node of the mapping file, with only one attribute The namespace namespace is used to distinguish different mappers. It is globally unique and the full name of the DAO interface bound to the namespace, that is, interface-oriented programming. The mapper here is equivalent to the implementation class of the interface.

cache - Configure the cache for the given namespace.

cache-ref – Reference cache configuration from other namespaces.

resultMap – The most complex and powerful element, used to describe how to load your objects from the database result set.

parameterMap – has been deprecated! Old-school style parameter mapping. Inline parameters are preferred, this element may be removed in the future. It will not be recorded here.

sql – SQL block that can be reused and referenced by other statements.

insert – Mapping insert statement

update – Mapping update statement

delete – Mapping delete statement

select – Mapping query statement

1: Use select to complete conditional query

Use tool idea and mysql database

Create entity class

public class student {private int stuId;private String  stuName;private grade getGrade;private  int stuAge;public grade getGetGrade() {return getGrade;
    }public void setGetGrade(grade getGrade) {this.getGrade = getGrade;
    }public int getStuAge() {return stuAge;
    }   public student(int id,String name){

   }   public student(){}public void setStuAge(int stuAge) {this.stuAge = stuAge;
    }public int getStuId() {return stuId;
    }public void setStuId(int stuId) {this.stuId = stuId;
    }public String getStuName() {return stuName;
    }public void setStuName(String stuName) {this.stuName = stuName;
    }
}

Use select Complete conditional query

1: First configure mapper to use resultType

<!--模糊查询   使用resultType返回结果集-->    
    <select>* from student where stuName like CONCAT('%',#{stuName},'%'</select>

Test class

 public  void Test() throws IOException {

        studentDao dao = MyBatis.getSessionTwo().getMapper(studentDao.class);
        List<student> list = dao.getAllStudentByLike("z");for (student item:list) {
            System.out.println("----------"+item.getStuName());
        }
}</student>

In addition, in addition to javaBean, the complex types supported by parameterType also include the Map type

That is, modify the Mapper

 <!--模糊查询-->
    <select>select * from student where stuName like CONCAT('%',#{stuName},'%')</select>

and then create one in the test class The HashMap collection can be used directly as a method parameter

studentDao dao = MyBatis.getSessionTwo().getMapper(studentDao.class);
        Map<string> userMap = new HashMap<string>();
        userMap.put("stuName","z");
        List<student> list = dao.getAllStudentByLike(userMap);for (student item:list) {
            System.out.println("----------"+item.getStuName());
        }</student></string></string>

But the key value of the map collection must be the same as the field name in the class.

2: Use resultMap to complete two-table query

For example, if the primary key id of the student table is associated with the class table, if you use resultType, you can only display its id, but in practice, you often focus on Class name, all need to use resultMap to map custom results.

<resultmap>
<id></id>
        <result></result>
        <result>
       
    </result></resultmap>

//sql语句
select * from student,grade

resultType directly represents the return type, including basic types and complex data types

resultMap is a reference to the external resultMap, and the id corresponding to the resultMap indicates that the return result is mapped to Which resultMap. : His application scenarios are: database field information is inconsistent with object attributes or complex joint queries need to be done to freely control the mapping results.

In addition, in the select element of MyBatis, resultType and resultMap are essentially the same, both are Map data structures. But both cannot exist at the same time.

Three: Use the automatic mapping level of resultMap

MyBatis is divided into three mapping levels

>NONE: Automatic matching is prohibited

>PARTIAL :(Default): Automatically match all attributes except those with internal nesting (association, collection)

>FULL: Automatically match all

Set autoMappingBehavior in the large configuration

 <settings>   <!--设置resultMap的自动映射级别为Full(自动匹配所有)--><setting></setting>   <!--FULL要大写··--> </settings>

When setting the value of autoMappingBehavior to FULL, there is no need to configure the nodes under resultMap. It will automatically match according to the database

Four: Use update to complete the modification

 <update>update student set stuName=#{0} where stuId=#{1}</update>

Here we use a relatively simple placeholder as a parameter. Just fill in the parameters directly in the test class

5: Use the attribute association that maps complex types

The previous result can only be mapped to a certain "simple type" attribute of javaBean, basic data type and packaging class, etc./

But when you want to map properties of complex types, you need to use association. Complex classes: that is, there is another javaBean in a javaBean, but association only handles one-to-one relationships.

        stuAge;

   。。。。。省略封装

 <resultmap>
       <!-- <id property="stuId" column="stuId"></id>
        <result property="stuName" column="stuName"></result>-->
        <!--关联另一个 属性-->
        <association>
       <!-- <id property="gradeId" javaType="Integer" column="gradeId"></id>
       <result property="gradeName" javaType="String" column="gradeName"></result>-->
        </association>
    </resultmap>
    <!--这里使用了自动匹配-->
<select> SELECT * FROM student,grade WHERE student.stuGrade=grade.gradeId</select>

测试类里直接调用即可

六:前面说到association仅处理一对一的管理关系

    如果要处理一对多的关系,则需要使用collection,它与 association元素差不多,但它映射的属性是一个集合列表,即javaBean内部嵌套一个复杂数据类型属性。

javaBean

  private int gradeId;private String gradeName;private List<student> gatStudent;</student>
 <resultmap>
        <!--<id property="gradeId" column="gradeId"></id>
        <result property="gradeName" column="gradeName"></result>-->
        <collection>
             <!-- <id property="stuId" column="stuId"></id>
              <result property="stuName" column="stuName"></result>-->
        </collection>
    </resultmap>
 <!--查询对应年级的student-->
    <select>   select * from student,grade where stuGrade = gradeId and gradeId=1
    </select>

The above is the detailed content of Example tutorial of sql mapping file. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software