Spring Boot-mybatis Full Annotation (3)

Source: Internet
Author: User

Pom.xml
<!--Introduction MyBatis--  <dependency>      <groupId>org.mybatis.spring.boot</groupId>      <artifactId>mybatis-spring-boot-starter</artifactId>      <version>1.3.  0</version>  </dependency>  <!--mybatis page plug-in-  <dependency>      < Groupid>com.github.pagehelper</groupid>      <artifactid>pagehelper-spring-boot-starter</ artifactid>      <version>1.1.  1</version>  </dependency>  
Basic SQL OperationsSpring boot has automatically implemented all MyBatis configurations, and the database can be manipulated directly by 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 additions and deletions to use @insert @[email protected]List<user>: Returns the collection. If only one result is returned, the return value is user. If the return value of the method is intUser param: parameter, #{id} is the ID value of the Param objectScan Mapper
    1. @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 and DAO self-contained, and @controller, @Service Echo, the overall structure is more excellent

Hump naming

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  
result mapping @resultsIf 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 the result mapping, 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>

Reusable @resultsassign ID to user when declaring
@Results (id= "user", value={      @Result (property= "NnNn", column= "Nn_nn")  })  

In other methods, duplicate the result mapping with ID user

@ResultMap ("user")  
Print SQL logs to the consoleAdd 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 consoleThe first line:==> to the left is the execution SQL interface and its method, the right is the execution statementsecond line: Pass parameter 1,string typeLine three: Find a row of datapage OutThe 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); }  
execution principle: Pagehelper.startpage will intercept the next SQL, that is, Mybatisdao.findall () SQL. 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 completedCallback IDAssuming 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 followsDAO Layerusegeneratedkeys=true: Gets the primary key generated by the databasekeyproperty= "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 ());  
Control DeskStored Proceduresthis 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 Layermode=in: Incoming parameter, is User.IDmode=out: Outgoing parameter, is User.Namestatementtype.callable: Description This is a stored procedure
@Select ("callHello (#{id,mode=in,jdbctype=varchar},#{name,mode=out,jdbctype=varchar})"  )  @Options (StatementType= statementtype.callable)  publicvoid Call (user user);  

Service Layer

 Public void Call () {      new  User ();      User.setid ("+");      Mybatisdao.call (user);      System. out. println (User.getname ());  
Execution Results

Spring Boot-mybatis Full Annotation (3)

Related Article

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.