Spring boot + mybatis Perfect integration

Source: Internet
Author: User
Tags assert

A new project has been launched in these two days because the project team members have been using MyBatis, although the individual prefers the minimalist model of JPA, but for the project to maintain the uniformity of the technology selection or set the MyBatis. On the internet to find a bit about the spring boot and mybatis combination of the relevant information, a variety of forms have, see the people tired, combined with the MyBatis official demo and documents finally found the most simple two models, spent a day summing up after sharing out.

ORM Framework is the essence of simplified programming in the operation of the database coding, development to now basically two left, one is claimed that can not write a SQL hibernate, one is flexible to debug dynamic SQL MyBatis, both have characteristics, In enterprise-level system development can be flexibly used in accordance with the requirements. Discover an interesting phenomenon: traditional enterprises mostly like to use hibernate, the Internet industry usually use MyBatis.

Hibernate feature is that all SQL is generated with Java code, do not jump out of the program to write (see) SQL, with programmatic integrity, the development to the top is the spring data JPA this pattern, basically based on the method name can generate the corresponding SQL, I don't know much about it. The last article Springboot (v): The use of spring data JPA.

The initial use of mybatis is cumbersome, requiring a variety of configuration files, entity classes, DAO layer mapping associations, and a large push to other configurations. Of course, MyBatis also found this disadvantage, initially developed generator can automatically produce entity classes, configuration files and DAO layer code based on table results, can reduce the amount of development; Later, a lot of optimizations can be made using annotations, automatically managing DAO layers and configuration files, etc. Development to the top is today to talk about this mode, Mybatis-spring-boot-starter is Springboot+mybatis can be fully annotated without configuration files, can also be simple configuration easy to use.

Now think of spring boot as a cool thing, anything that links to spring boot is simple. Mybatis-spring-boot-starter

Official note: MyBatis Spring-boot-starter'll help your use MyBatis with Spring Boot
In fact, mybatis see Spring boot so hot also developed a set of solutions to join in the fun, but this together does solve a lot of problems, use it really smooth a lot. Mybatis-spring-boot-starter There are two main solutions, one is to use annotations to solve all problems, one is the simplified old tradition.

Of course, any mode needs to first introduce the Mybatis-spring-boot-starter Pom file, now the latest version is 1.1.1 (just fast to 11:))

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId> mybatis-spring-boot-starter</artifactid>
    <version>1.1.1</version>
</dependency >

okay, come down. Two development models are introduced No profile annotation version

It 's all done with annotations. 1 Add related maven files

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <ar tifactid>spring-boot-starter</artifactid> </dependency> <dependency> <groupid>o Rg.springframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> < scope>test</scope> </dependency> <dependency> <groupid>org.springframework.boot </groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <depe Ndency> <groupId>org.mybatis.spring.boot</groupId> <artifactid>mybatis-spring-boot-st
        arter</artifactid> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </depend Ency> <dependEncy> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-devtools&lt
 ;/artifactid> <optional>true</optional> </dependency> </dependencies>

The full POM package is not posted here, we look directly at the source 2, application.properties add related configuration

mybatis.type-aliases-package=com.neo.entity

spring.datasource.driverClassName = Com.mysql.jdbc.Driver
Spring.datasource.url = Jdbc:mysql://localhost:3306/test1?useunicode=true&characterencoding=utf-8
Spring.datasource.username = root
Spring.datasource.password = root

Springboot will automatically load spring.datasource.* related configuration, the data source will be automatically injected into the Sqlsessionfactory, Sqlsessionfactory will automatically inject into the mapper, you don't have to control everything, Just pick it up and use it.

To add a mapper packet scan in the startup class @mapperscan

@SpringBootApplication
@MapperScan ("Com.neo.mapper") public
class Application {public

    static void Main (string[] args) {
        springapplication.run (application.class, args);
    }
}

or add the annotation directly above the Mapper class @mapper, suggest to use above kind, otherwise each Mapper adds an annotation also very troublesome 3, Development mapper

The third step is the most critical piece, the SQL production is here

Public interface Usermapper {

    @Select (' select *
    from users ') @Results ({@Result (property  = "Usersex") Column = "User_sex", Javatype = Usersexenum.class),
        @Result (property = "nickname", column = "Nick_name")
    })
    List<userentity> getAll ();

    @Select ("Select * from users WHERE id = #{id}")
    @Results ({
        @Result (property = "Usersex",  column = "User_se X ", Javatype = Usersexenum.class),
        @Result (property =" nickname ", column =" Nick_name ")
    })
    userentity GetOne (Long ID);

    @Insert (Insert into Users (username,password,user_sex) VALUES (#{username}, #{password}, #{usersex})
    void Insert (userentity user);

    @Update ("Update users SET username=#{username},nick_name=#{nickname} WHERE ID =#{id}")
    void Update (userentity user);

    @Delete ("Delete from users WHERE ID =#{id}")
    void Delete (Long id);


In order to get closer to the production I specifically put user_sex, nick_name two attributes in the database underlined and entity class attribute names are inconsistent, in addition user_sex use the enumeration @Select is the annotation of the query class, all queries use this @Result to decorate the returned result set, The associated entity Class property and database field one by one correspond and do not need this property to be decorated if the entity class attribute and the database property name are consistent. @Insert inserted into the database, the direct incoming entity class automatically resolves the attribute to the corresponding value @Update is responsible for modifying it, or it can be passed directly to the object @delete responsible for deleting

Learn more about properties reference here

Notice the difference between using the # symbol and the $ symbol:

This is example creates a prepared statement, something like select * from teacher where name =?;
@Select ("Select * from teacher where name = #{name}")
teacher Selectteachforgivenname (@Param ("name") String name); c3/>//This example creates n inlined statement, something like select * from teacher where name = ' Somename ';
@Select ("select * from teacher where name = ' ${name} '")
teacher Selectteachforgivenname (@Param ("name") String name);
4. Use

The above three steps basically completes the related DAO layer development, uses the time as the ordinary class injects enters to be possible

 @RunWith (Springrunner.class) @SpringBootTest public class Usermappertest {@Autowired private usermapper use

    Rmapper; @Test public void Testinsert () throws Exception {Usermapper.insert (new userentity ("AA", "a123456", Usersexenu
        M.man));
        Usermapper.insert (New userentity ("BB", "b123456", Usersexenum.woman));

        Usermapper.insert (New Userentity ("CC", "b123456", Usersexenum.woman));
    Assert.assertequals (3, Usermapper.getall (). Size ());
        @Test public void Testquery () throws Exception {list<userentity> users = Usermapper.getall ();
    System.out.println (Users.tostring ());
        @Test public void Testupdate () throws Exception {userentity user = Usermapper.getone (3l);
        System.out.println (User.tostring ());
        User.setnickname ("Neo");
        Usermapper.update (user);
    Assert.asserttrue (("Neo". Equals (Usermapper.getone (3l). Getnickname ())); }
}

Source code in the Controler layer has complete additions and deletions to check, here is not posted
Source code here spring-boot-mybatis-annotation the
minimalist XML version

Minimalist XML version to maintain the old tradition of mapping files, the main embodiment of optimization is not needed to implement DAO is the implementation layer, the system will automatically according to the method name in the mapping file to find the corresponding SQL. 1, configuration

The pom file is the same as the previous version, except that application.properties adds the following configuration

Mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/ Mapper/*.xml

Specifies the address of the MyBatis base configuration file and entity class mapping file

Mybatis-config.xml Configuration

<configuration>
    <typeAliases>
        <typealias alias= "Integer" type= "Java.lang.Integer"/>
        <typealias alias= "Long" type= "Java.lang.Long"/> <typealias alias= "HashMap"
        Java.util.HashMap "/> <typealias alias= linkedhashmap" type= "Java.util.LinkedHashMap"/>
        < Typealias alias= "ArrayList" type= "java.util.ArrayList"/> <typealias alias= "LinkedList"
        Java.util.LinkedList "/>
    </typeAliases>
</configuration>

You can also add some mybatis base configurations here 2, add user's mapping file

<mapper namespace= "Com.neo.mapper.UserMapper" > <resultmap id= "Baseresultmap" Com.neo.entity.UserEntity "> <id column=" id "property=" id "jdbctype=" BIGINT "/> <result column = "UserName" property= "UserName" jdbctype= "VARCHAR"/> <result column= "PassWord" property= "PassWord" Jdbctype
        = "VARCHAR"/> <result column= "user_sex" property= "Usersex" javatype= "Com.neo.enums.UserSexEnum"/> <result column= "Nick_name" property= "nickname" jdbctype= "VARCHAR"/> </resultMap> <sql id= "Base_c Olumn_list "> ID, UserName, PassWord, User_sex, nick_name </sql> <select id=" GetAll "Resultma p= "Baseresultmap" > SELECT <include refid= "Base_column_list"/> from users </select > <select id= "getone" parametertype= "Java.lang.Long" resultmap= "Baseresultmap" > select < Include refid= "Base_column_list"/> FROM users WHERE id = #{id} </select> <insert id= "Insert" parametertype= "com.neo.entity.UserEntity" > INSERT into Users (username,password,user_sex) VALUES (#{usernam e}, #{password}, #{usersex}) </insert> <update id= "Update" parametertype= "Com.neo.entity.UserEntity"
       ;
        UPDATE users SET <if test= "userName!= null" >username = #{username},</if> 
            <if test= "PassWord!= null" >password = #{password},</if> nick_name = #{nickname} WHERE
             id = #{id} </update> <delete id= "delete" parametertype= "Java.lang.Long" > Delete from
 Users WHERE ID =#{id} </delete> </mapper>

is actually moving the mapper SQL from the previous version to the XML here . 3, write the DAO layer code

Public interface Usermapper {

    list<userentity> getAll ();

    Userentity GetOne (Long ID);

    void Insert (userentity user);

    void update (userentity user);

    void Delete (Long id);


compared to the previous step, all we have left is the interface method 4. Use

There's no difference between using and previous versions, so let's look at the code.

XML configuration version How to choose

The two modes have their own characteristics, the annotation version is suitable for simple and fast mode, in fact, such as the current popular micro-service mode, a micro-service will be corresponding to a self database, multiple table connection query needs will be greatly reduced, will become more and more suitable for this model.

Older traditional mode than suitable for large-scale projects, can be flexible dynamic generation of SQL, easy to adjust SQL, but also have a good, voluminous write the feeling of SQL.

Full Code Address

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.