Home php教程 PHP开发 Use mybatis elegantly

Use mybatis elegantly

Nov 22, 2016 pm 01:34 PM
mybatis

Mybatis is quite troublesome to use in the initial stage. It requires various configuration files, entity classes, dao layer mapping associations, and a lot of other configurations. Of course, mybatis has also discovered this shortcoming. In the early stage, it developed a generator that can automatically produce entity classes, configuration files and DAO layer codes based on table results, which can reduce part of the development workload. In the later period, a lot of optimization was also carried out to use annotations and automatically manage DAOs. Layers and configuration files, etc., have developed to the top and this is the model I will talk about today. Mybatis-spring-boot-starter is springboot+mybatis, which can be fully annotated without a configuration file, and can also be easily configured and easily used.

Now think about spring boot, it is awesome. Anything related to spring boot will simplify the complexity.

mybatis-spring-boot-starter

Official description: MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
In fact, myBatis saw that spring boot was so popular and developed a solution to join in the fun, but this It really solves a lot of problems and makes it much smoother to use. mybatis-spring-boot-starter mainly has two solutions, one is to use annotations to solve all problems, and the other is the simplified old tradition.

Of course, any mode needs to first introduce the pom file of mybatis-spring-boot-starter. The latest version now is 1.1.1

1

2

3

4

<dependency>

    <groupId>org.mybatis.spring.boot</groupId>

    <artifactId>mybatis-spring-boot-starter</artifactId>

    <version>1.1.1</version></dependency>

Copy after login

Okay, let’s introduce the two development modes separately

No configuration file annotation version

That’s everything Use annotations to get it done.

1 Add related maven files

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter</artifactId>

    </dependency>

    <dependency>

        <groupId>org.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>

    <dependency>

        <groupId>org.mybatis.spring.boot</groupId>

        <artifactId>mybatis-spring-boot-starter</artifactId>

        <version>1.1.1</version>

    </dependency>

     <dependency>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

    </dependency>

     <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <optional>true</optional>

    </dependency></dependencies>

Copy after login

The complete pom package will not be posted here. You can look at the source code directly

2. Application.properties Add related configurations

1

2

3

4

5

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-8spring.datasource.username = root

spring.datasource.password = root

Copy after login

springboot will automatically load spring.datasource.* related configurations and data The source will be automatically injected into sqlSessionFactory, and sqlSessionFactory will be automatically injected into Mapper. By the way, you don’t have to worry about anything, just pick it up and use it.

Add @MapperScan

1

2

3

4

5

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

public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}

Copy after login

to the startup class to scan the mapper package or directly add the annotation @Mapper to the Mapper class. It is recommended to use the above one, otherwise it will be quite troublesome to add annotations to each mapper

3. Develop Mapper

The third step is the most critical one. SQL production is all here

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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_sex", 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);

 

}

Copy after login

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

1

2

3

4

5

6

7

// This 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);

 

// 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);

Copy after login

4. Using the above three steps, the development of the relevant dao layer is basically completed. When used, it can be injected as a normal class

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTest {    @Autowired

    private UserMapper UserMapper;    @Test

    public void testInsert() throws Exception {

        UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.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())));

    }

}

Copy after login

Minimalist XML version

Minimalist XML version maintains the old tradition of mapping files. The optimization is mainly reflected in the implementation layer that does not need to implement dao. The system will automatically The method name finds the corresponding sql in the mapping file.

1、配置

pom文件和上个版本一样,只是application.properties新增以下配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xm

1

2

mybatis.config-locations=classpath:mybatis/mybatis-config.xml

mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

Copy after login

指定了mybatis基础配置文件和实体类映射文件的地址

mybatis-config.xml 配置

1

2

3

4

5

6

7

8

9

<configuration>

    <typeAliases>

        <typeAlias alias="Integer" type="java.lang.Integer" />

        <typeAlias alias="Long" type="java.lang.Long" />

        <typeAlias alias="HashMap" type="java.util.HashMap" />

        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />

        <typeAlias alias="ArrayList" type="java.util.ArrayList" />

        <typeAlias alias="LinkedList" type="java.util.LinkedList" />

    </typeAliases></configuration>

Copy after login

这里也可以添加一些mybatis基础的配置

2、添加User的映射文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

<mapper namespace="com.neo.mapper.UserMapper" >

    <resultMap id="BaseResultMap" type="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_Column_List" >

        id, userName, passWord, user_sex, nick_name    </sql>

 

    <select id="getAll" resultMap="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

               (#{userName}, #{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>

Copy after login

其实就是把上个版本中mapper的sql搬到了这里的xml中了

3、编写Dao层的代码

1

2

3

4

5

6

7

8

9

10

11

12

13

public interface UserMapper {

 

    List<UserEntity> getAll();

 

    UserEntity getOne(Long id);

 

    void insert(UserEntity user);

 

    void update(UserEntity user);

 

    void delete(Long id);

 

}

Copy after login

对比上一步这里全部只剩了接口方法

如何选择

两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自已的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。

老传统模式比适合大型项目,可以灵活的动态生成SQL,方便调整SQL,也有痛痛快快,洋洋洒洒的写SQL的感觉。


Statement of this Website
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iBatis vs. MyBatis: Which one is better for you? iBatis vs. MyBatis: Which one is better for you? Feb 19, 2024 pm 04:38 PM

iBatis vs. MyBatis: Which one is better for you?

Various ways to implement batch deletion operations in MyBatis Various ways to implement batch deletion operations in MyBatis Feb 19, 2024 pm 07:31 PM

Various ways to implement batch deletion operations in MyBatis

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

Comparative analysis of the functions and performance of JPA and MyBatis

Detailed explanation of how to use MyBatis batch delete statements Detailed explanation of how to use MyBatis batch delete statements Feb 20, 2024 am 08:31 AM

Detailed explanation of how to use MyBatis batch delete statements

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency?

Detailed explanation of MyBatis one-to-many query configuration: solving common related query problems Detailed explanation of MyBatis one-to-many query configuration: solving common related query problems Feb 22, 2024 pm 02:18 PM

Detailed explanation of MyBatis one-to-many query configuration: solving common related query problems

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache

See all articles