Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Building microservices: how to use mybatis gracefully

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article is reproduced and released by www.29sl.com: a new project has been launched these two days because the project team members have been using mybatis. Although I prefer the minimalist mode of jpa, I still choose mybatis in order to maintain the unity of the project. I went to the Internet to find the relevant information about the combination of spring boot and mybatis. It was tiring to see it in a variety of forms. I finally found the simplest two modes by combining mybatis's official demo and documentation, which took me a day to sum up and share.

The essence of orm framework is to simplify the coding of operating database in programming. Up to now, there are basically only two, one is hibernate that claims that you don't have to write a sentence of sql, and the other is mybatis that can flexibly debug dynamic sql. Both of them have their own characteristics and can be used flexibly according to the requirements in the development of enterprise-level systems. Found an interesting phenomenon: most of the traditional enterprises like to use hibernate, while the Internet industry usually uses mybatis.

The characteristic of hibernate is that all sql are generated with Java code, there is no need to jump out of the program to write (see) sql, there is programming integrity, the development to the top is spring data jpa this mode, basically according to the method name can generate the corresponding sql, there is not much to understand my last article to build micro services: the use of spring data jpa (http://www.ityouknow.com).

The initial use of mybatis is cumbersome, requiring various configuration files, entity classes, dao layer mapping associations, and a host of other configurations. Of course, mybatis also found this malpractice. The initial development of generator can automatically produce entity classes, configuration files and dao layer code according to the table results, which can reduce part of the development volume. Later also made a lot of optimization can use annotations, automatic management of dao layers and configuration files, etc., to the top of the development is today to talk about this mode, mybatis-spring-boot-starter is springboot+mybatis can be completely annotated without configuration files, but also simple configuration easy to get started.

Now think about spring boot is a cow, anything associated with spring boot is reduced to complexity.

Mybatis-spring-boot-starter

Official statement: MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot

In fact, even mybatis saw that spring boot was so hot and developed a solution to join the fun, but this solution did solve a lot of problems and made it much easier to use. There are two main solutions to mybatis-spring-boot-starter, one is to use annotations to solve all problems, and the other is the simplified old tradition.

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

Org.mybatis.spring.boot

Mybatis-spring-boot-starter

1.1.1

All right, let's introduce the two development modes respectively.

No profile annotated version

Is to do everything with annotations.

1. Add related maven files

Org.springframework.boot

Spring-boot-starter

Org.springframework.boot

Spring-boot-starter-test

Test

Org.springframework.boot

Spring-boot-starter-web

Org.mybatis.spring.boot

Mybatis-spring-boot-starter

1.1.1

Mysql

Mysql-connector-java

Org.springframework.boot

Spring-boot-devtools

True

Complete pom package will not be posted here, we will directly look at the source code.

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

Spring.datasource.password = root

Springboot will automatically load spring.datasource.*-related configurations, the data 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 everything, just pick it up and use it.

Add @ MapperScan to scan mapper packages in the startup class

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

Public static void main (String [] args) {

SpringApplication.run (Application.class, args)

}

}

Or add the annotation @ Mapper directly to the Mapper class, and it is recommended to use the above, otherwise it will be troublesome to add an annotation to each mapper.

3. Develop Mapper

The third step is the most critical piece. Sql production is all 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 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)

}

In order to get closer to production, I specially underlined user_sex and nick_name attributes in the database and inconsistent entity class attribute names, and user_sex used enumerations.

@ Select is the annotation of the query class, which is used by all queries

@ Result modifies the returned result set, and the associated entity class attribute corresponds to the database field one by one. If the entity class attribute and the database attribute name are the same, this attribute is not needed to decorate.

@ Insert is inserted into the database. Passing the entity class directly will automatically resolve the attribute to the corresponding value.

@ Update is responsible for the modification, or you can pass in the object directly.

@ delete is responsible for deletion

For more information on attributes, please see http://www.mybatis.org/mybatis-3/zh/java-api.html here.

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

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

4. Use

The above three steps have basically completed the development of the relevant dao layer, and you can enter it as a normal class injection when using it.

@ 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 users = UserMapper.getAll ()

System.out.println (users.toString ())

} @ Test

Public void testUpdate () throws Exception {

UserEntity user = UserMapper.getOne (31)

System.out.println (user.toString ())

User.setNickName ("neo")

UserMapper.update (user)

Assert.assertTrue (("neo" .equals (UserMapper.getOne (31). GetNickName ()

}

}

The controler layer in the source code has complete additions, deletions, modifications and queries, so it will not be posted here. The source code is here spring-boot-mybatis-annotation (https://github.com/ityouknow/spring-boot-starter/tree/master/mybatis-spring-boot/spring-boot-mybatis-annotation)

Minimalist xml version

The minimalist version of xml keeps the old tradition of mapping files, and the optimization is mainly reflected in the implementation layer that does not need to implement dao, and the system will automatically find the corresponding sql in the mapping file according to the method name.

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 the entity class mapping file.

Mybatis-config.xml configuration

You can also add some basic mybatis configurations here.

two。 Add a mapping file for User

Id, userName, passWord, user_sex, nick_name

SELECT

FROM users

SELECT

FROM users

WHERE id = # {id}

INSERT INTO

Users

(userName,passWord,user_sex)

VALUES

(# {userName}, # {passWord}, # {userSex})

UPDATE

Users

SET

UserName = # {userName}

PassWord = # {passWord}

Nick_name = # {nickName}

WHERE

Id = # {id}

DELETE FROM

Users

WHERE

Id = # {id}

In fact, the sql of mapper in the last version has been moved to the xml here.

3. Write code for the Dao layer

Public interface UserMapper {

List getAll ()

UserEntity getOne (Long id)

Void insert (UserEntity user)

Void update (UserEntity user)

Void delete (Long id)

}

Compared with the previous step, all that is left is the interface method.

4. Use

There is no difference between the use and the previous version, let's just look at the code.

The old traditional optimized version code is here for https://github.com/ityouknow/spring-boot-starter/tree/master/mybatis-spring-boot/spring-boot-mybatis-xml.

How to choose

The two modes have their own characteristics, and the annotated version is suitable for simple and fast schemes. in fact, like the popular micro-service model, a micro-service corresponds to its own database, and the demand for multi-table join queries will be greatly reduced. will be more and more suitable for this mode.

The old traditional mode is more suitable for large-scale projects, it can generate SQL flexibly and dynamically, and it is convenient to adjust SQL. It also has the feeling of writing SQL happily and freely.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report