This article highlights the example code of Spring boot MyBatis annotation
1, Pom.xml
// Introducing MyBatis<dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactid>mybatis-spring-boot-starter</artifactid> <version>1.3. 0// mybatis page plug-ins <dependency> <groupid>com.github.pagehelper</groupid > <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.1 . 1</version> </dependency>
2. Basic SQL Operations
Spring boot has automatically implemented all MyBatis configurations, directly writing the DAO interface
@Mapper Public Interface Mybatisdao { @Select ("select * from user where id = #{id}") Public list<user> FindByID (User param);
@Mapper: Declares a MyBatis DAO interface that will be scanned by spring boot to
@Select: Declare a Query method, the corresponding increase, delete, change use: @Insert, @Delete, @Update
List<user>: Returns the collection. If only one result is returned, the return value is user. If the increment, delete, and change method, the return value is int
User param: Parameter, #{id} is the ID value of the Param object
3, scanning mapper
@MapperScan("hello.dao")
By adding the above annotations on the configuration class, you can scan all the interfaces in the DAO package instead of writing @mapper annotations in each DAO, but this will increase the coupling degree .
And @mapper can be self-contained with DAO, with @controller, @Service, the overall structure is more elegant
4, Hump name
Add the following configuration to the properties, and after executing the query, you can automatically convert the database's NN_NN format field to the hump named parameter in the Java result set object
Mybatis.configuration.mapunderscoretocamelcase=True
5. Result mapping @results
If the result set is not a Java object but the column name in Map,map is the same as the NN_NN in the database, the hump is not automatically converted .
You can use @Result to indicate a result map, as well as for Java objects
@Results ({ @Resultproperty ="nnNn", column="nn_nn ") }) @Select ("select * from user") public list<map> findAll ();
Using list<map> does not need to maintain pojo, which is suitable for scenarios where database fields are uncertain or frequently changing. But the program is less readable and maintainable than list<user>
6. Reusable @results
Assign ID to user when declaring
@Results (id="user", value={ @Result (property ="nnNn ", column="nn_nn")})
In other methods, the result mapping with ID user is reused:@ResultMap("user")
7. Print SQL log to console
Add the following configuration in application.properties:logging.level. Your package name. MyBatis Interface Pack =debug
When you execute SQL, the SQL log is printed in the console
The first line:==> to the left is the execution SQL interface and its method, the right is the execution statement
Second line: Pass parameter 1,string type
Line three: Find a row of data
8. Paging
The first part of the Pom.xml is to introduce the page plug-in at the beginning of the article, the paging logic written on the service layer.
@Service @transactional Public classHelloserviceimpl {@Autowired Mybatisdao Mybatisdao; Public voidfind () {//page plug-in: Query page 1th, 10 rows per pagePage<user> Page =pagehelper.startpage (1,Ten); Mybatisdao.findall (); //total number of rows in the data tablepage.gettotal (); //Total rows for paged query resultspage.size (); //The first user object, refer to list, ordinal 0 is the first element, and so onPage.Get(0); }
Principle of execution:
Pagehelper.startpage will intercept SQL for the next SQL, which is Mybatisdao.findall (). And according to the current database syntax, the SQL is transformed into a high-performance paging SQL, but also query the total number of rows of the table, in particular, you can see the SQL log.
Pagehelper.startpage and Mybatisdao.findall () are best to keep up with each other, not in the middle of the logic, or it might be a bug.
Page<user> page: Equivalent to a list collection, the FindAll () method will assign values to the relevant parameters of the Page object when the query is completed
9. Callback ID
Assuming that the ID primary key for the database table is automatically growing, add a piece of data now and want to get the ID of this data autogrow, as follows
DAO layer
Usegeneratedkeys=true: Gets the primary key generated by the database
keyproperty= "id": The id attribute of the user Param object to which the primary key value is stored
@Insert ("Insert into user (name) values (#{name})") @Options (Usegeneratedkeys= true, keyproperty="ID") publicint Add ( User param);
Service Layer
New User (); User.setname ("Tom"); Mybatisdao.add (user); System. out. println (" callback ID value:"+user.getid ());
10. Control Station
Stored Procedures
This is a MySQL stored procedure, passing in an ID value, querying the name value based on this ID and as an outgoing parameter
DELIMITER $$ CREATE PROCEDURE ' Hello ' (in id_in varchar(Ten), out name_out varchar) BEGIN SELECT NAME into name_out from USER WHERE id=id_in; end$$ DELIMITER;
DAO layer
Mode=in: Incoming parameter, is user.id
Mode=out: Outgoing parameter, is User.Name
Statementtype.callable: Description This is a stored procedure
@Select ("callHello (#{id,mode=in,jdbctype=varchar},#{name,mode=out,jdbctype=varchar})" ) @Options (statementtype=publicvoid call (user user);
Service Layer
Public void Call () { new User (); User.setid ("+"); Mybatisdao.call (user); System. out . println (User.getname ());}
Execution results
Full annotation of spring boot MyBatis