Spring Boot Learning Note (ii)-Integrated MyBatis

Source: Internet
Author: User

Spring Boot Learning Note (ii)-Integrated MyBatis

Spring Boot integrates the MyBatis and implements the mapping through annotations.

Integrated MyBatis

Take the Spring Boot Learning Note (a)-Hello world as the base project, add the following dependencies in Pom.xml

<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 >   <version>5.1.21</version></dependency>

Add the MySQL connection configuration under the Application.properties file (remember not to leave a space at the end of the line, otherwise the Com.mysql.jdbc.Driver class not Found error, in fact, it just contains a space resulting in the missing class)

spring.datasource.url=jdbc:mysql://localhost:3306/Testspring.datasource.username= Rootspring.datasource.password=spring.datasource.driver-class-name=com.mysql.jdbc.driver

As with other spring boot projects, the basic configuration is simple and concise, and the following is a quick and easy way to access the database using MyBatis.

Add the Com.latteyan.entity package and add the user class

 Packagecom.latteyan.entity;Importjava.io.Serializable; Public classUserImplementsserializable{Private Static Final LongSerialversionuid = 8002149736589557777L; PrivateLong ID; PrivateString name; PrivateInteger age;  PublicLong getId () {returnID; }     Public voidsetId (Long id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicInteger getage () {returnAge ; }     Public voidsetage (Integer age) { This. Age =Age ; }}

Add the Com.latteyan.dao package and add the Usermapper interface

 PackageCom.latteyan.dao;Importjava.util.List;ImportJava.util.Map;ImportCom.latteyan.entity.User;Importorg.apache.ibatis.annotations.*; @Mapper Public InterfaceUsermapper {//New with parameter@Insert ("Insert into USER (NAME, age) VALUES (#{name}, #{age})")    intInsertbyparameter (@Param ("name") String name, @Param ("Age") (Integer age); //New via Map@Insert ("Insert into USER (NAME, age) VALUES (#{name,jdbctype=varchar}, #{age,jdbctype=integer})")    intInsertbymap (map<string, object>map); //New With Object@Insert ("Insert into USER (NAME, age) VALUES (#{name}, #{age})")    intinsertbyobject (user user); //Delete by Id@Delete ("Delete from user WHERE ID =#{id}")    voidDelete (Long ID); //Update@Update ("Update user SET Age=#{age} WHERE Name=#{name}")    voidUpdate (user user); //Find by Parameter@Select ("select * from USER WHERE NAME = #{name}") User findbyname (@Param ("Name") String name); //by @results, the binding return value@Results ({@Result ( property= "Name", column = "Name"), @Result ( property= ' age ', column = ' age ')}) @Select ("Select name, age from user") List<User>FindAll (); }
With the Usermapper interface, we can now access the functionality of the database.

Unit Test
 PackageCom.latteyan;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportOrg.junit.Assert;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner;ImportCom.latteyan.dao.UserMapper;ImportCom.latteyan.entity.User; the @RunWith (Springrunner.class) @SpringBootTest Public classspringbootapplicationtests {@AutowiredPrivateUsermapper Usermapper; @Test Public voidAdd ()throwsException {//Insert by parameterUsermapper.insertbyparameter ("Zhangshan", 20); //Insert by ObjectUser User =NewUser (); User.setage (21st); User.setname ("LiSi");                Usermapper.insertbyobject (user); //Insert by Mapmap<string, object> map =NewHashmap<>(); Map.put ("Name", "Huangwu"); Map.put ("Age", 22);                Usermapper.insertbymap (map); User Zhangshan= Usermapper.findbyname ("Zhangshan"); Assert.assertequals (20, Zhangshan.getage (). Intvalue ()); User LiSi= Usermapper.findbyname ("LiSi"); Assert.assertequals (21st, Lisi.getage (). Intvalue ()); User Huangwu= Usermapper.findbyname ("Huangwu"); Assert.assertequals (22, Huangwu.getage (). Intvalue ()); } @Test Public voidUdpate ()throwsException {User User= Usermapper.findbyname ("Zhangshan"); User.setage (50);                Usermapper.update (user); User= Usermapper.findbyname ("Zhangshan"); Assert.assertequals (50, User.getage (). Intvalue ());    Usermapper.delete (User.getid ()); } @Test Public voidFindAll ()throwsException {List<User> users =Usermapper.findall ();    Assert.assertnotnull (users); }}

Reference: http://blog.didispace.com/springbootmybatis/

Spring Boot Learning Note (ii)-Integrated MyBatis

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.