Springboo Machine integrated MyBatis and MySQL
1, adding dependencies
<?xml version= "1.0"?><Project Xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" > <modelversion >4.0.0</modelVersion> <!--project information Begin--<groupId>com.microservice</groupId> <arti Factid>spring-web</artifactid> <version>0.0.1-SNAPSHOT</version> <name>spring-web< /name> <url>http://maven.apache.org</url> <!--project information End--<!--property configuration Begin--<properties> <project.build.sourceencoding>u Tf-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</ Project.reporting.outputencoding> <java.version>1.8</java.version> </properties> <!-- Property configuration End-<!--parent dependency Begin--<parent> <GROUPID>ORG.SPRINGFRAMEWORK.BOOT</GROUPID&G T <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> <relativepath/> <!--lookup parent from repository--</parent> <!--parent dependency end-to-<d Ependencies> <!--Add a Web package Begin--<dependency> <groupid>org.springframework .boot</groupid> <artifactId>spring-boot-starter</artifactId> </dependency> <!--The package contains requestmapping RestconTroller and other annotations-<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-test</arti Factid> <scope>test</scope> </dependency> <!--add a Web package end---& lt;! --MyBatis dependency Begin--<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!--mybatis Dependency End--<!--mysql database configuration Begin---<dependency& Gt <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </depe Ndency> <!--mysql Database configuration end--<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope& Gt;test</scope> </dependency> </dependencies></project>
When you add this configuration, you need to be aware of the MyBatis and spring version conflict issues. If a conflict occurs, it can cause some strange problems, such as an annotation (@Mapper) not succeeding. To resolve this issue, refer to URL https://start.spring.io/, configuring the version.
2, adding configuration information
#系统中用到的参数配置 encoding format com.interview.question== = Jdbc:mysql://localhost : 3306/shop?useunicode=true&characterencoding=utf-8spring.datasource.url = jdbc:mysql:// Localhost:3306/shopspring.datasource.username == Root#mybatis Database mapping file configuration Mybatis.config- locations=classpath:mybatis/mybatis-config.xmlmybatis.mapper-locations=classpath:mybatis/mapper /* . XML
Mybatis-config.xml aliases for ———— data types
<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>
*.xml--Configuring the MyBatis database mapping file
such as Usermapper.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace= "Org.spring.web.mapper.UserMapper" >
<resultmap id= "Baseresultmap" type= "Org.spring.web.entity.User" >
<id column= "id" property= "id" jdbctype= "BIGINT"/>
<result column= "Age" property= "Age" jdbctype= "INTEGER"/>
<result column= "PassWord" property= "PassWord" jdbctype= "VARCHAR"/>
<result column= "user_name" property= "UserName" jdbctype= "VARCHAR"/>
</resultMap>
<sql id= "Base_column_list" >
ID, User_name,age, PassWord
</sql>
<!--query users--
<select id= "Selectuserbyid" resultmap= "Baseresultmap" parametertype= "Integer" >
Select
<include refid= "Base_column_list"/>
From user where Id=#{id}
</select>
<update id= "UpdateUser" parametertype= "Org.spring.web.entity.User" >
UPDATE
User
SET
<if test= "Age! = null and age!=" ">age = #{age},</if>
<if test= "PassWord! = null and password!=" ">password = #{password},</if>
user_name = #{username}
WHERE
id = #{id}
</update>
</mapper>
3,xxmapper.xml corresponds to the Xxmapper.java class, which corresponds to the Xxmapper.xml, which is the interface, where the method name and the SQL ID in the xxmapper.xml are consistent.
PackageOrg.spring.web.mapper;ImportOrg.apache.ibatis.annotations.Mapper;ImportOrg.spring.web.entity.User;Importorg.springframework.stereotype.Component;/*** * Project name: spring-web* Class Name: usermapper* class Description: * Creator: john* created: July 28, 2018 11:57:18 * Modified by: john* modified: July 28, 2018 a.m. 11 : 57:18* Change Notes: *@version**/@Mapper//@Component Public InterfaceUsermapper {/** User New*/ Public intinseruser (user user); PublicUser Selectuserbyid (Integer ID); Public intupdateUser (user user);}
@Mapper inject the class, you can also add @MapperScan ("Org.spring.web.mapper") directly in the startup class, where the parameters are where Xxmapper.java resides. @MapperScan ("") and adding @mapper on Xxmapper.java are the same.
4, write the database service interface layer
PackageOrg.spring.web.service;ImportOrg.spring.web.entity.User;ImportOrg.springframework.stereotype.Service;/*** * Project name: spring-web* Class Name: userservice* class Description: * Creator: john* created: July 28, 2018 11:52:50 * Modified by: john* modified: July 28, 2018 a.m. 11 : 52:50* Change Notes: *@version**/ Public InterfaceUserService { Public intinseruser (user user); PublicUser Selectuserbyid (Integer ID); Public intupdateUser (user user); PublicString GetUser ();}
Data Service Interface Implementation layer
PackageOrg.spring.web.service.serviceImpl;ImportJava.util.concurrent.TimeUnit;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportOrg.spring.web.entity.User;ImportOrg.spring.web.mapper.UserMapper;ImportOrg.spring.web.service.UserService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.data.redis.core.ValueOperations;ImportOrg.springframework.stereotype.Service;/*** * Project name: spring-web* Class Name: userserviceimpl* class Description: * Creator: john* created: July 28, 2018 11:53:16 * Modified by: john* modified: July 28, 2018 a.m. 11 : 53:16* Change Notes: *@version**/@Service Public classUserserviceimplImplementsuserservice{Private StaticLogger Logger =loggerfactory.getlogger (Userserviceimpl.class); @AutowiredPrivateUsermapper Usermapper; @AutowiredPrivateredistemplate redistemplate; Public intinseruser (user user) {return0; } Publicuser Selectuserbyid (Integer ID) {User user=Usermapper.selectuserbyid (ID); System.out.println ("User information based on user id>>" +id+ ">>>>>." +user); returnuser; } @Override Public intupdateUser (user user) {returnusermapper.updateuser (user); } @Override PublicString GetUser () {User User=NewUser (); User.setid (22); User.setusername ("Interview"); Valueoperations<string, user> operations=Redistemplate.opsforvalue (); Operations.set ("Com.yfli", user); Operations.set ("Com.neo.f", user,1, Timeunit.seconds); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } //redistemplate.delete ("com.neo.f"); BooleanExists=redistemplate.haskey ("Com.neo.f"); if(exists) {System.out.println ("Exists is true"); }Else{System.out.println ("Exists is false"); } User Redisuser=operations.get ("Com.yfli"); returnredisuser.tostring (); }}
The Data interface implementation layer adds @service annotations on it, and the interface layer does not have to add annotations. If the implementation layer does not add annotations, the Main method starts with an error.
5,controller Layer
PackageOrg.spring.web.controller;ImportOrg.spring.web.entity.User;ImportOrg.spring.web.service.UserService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;/*** * Project name: spring-web* Class Name: usercontroller* class Description: * Creator: john* created: July 28, 2018 12:15:36 * Modified by: john* modified: July 28, 2018 PM 12 : 15:36* Change Notes: *@version**/@RestController @requestmapping ("/USER") Public classUsercontroller {@Autowired userservice userservice; @RequestMapping ("/selectbyuserid") PublicUser Selectbyuserid (Integer ID) {ID=1; returnUserservice.selectuserbyid (ID); } @RequestMapping ("/updateuser") Public intupdateUser (user user) {User.setpassword ("222"); User.setusername (Hello); User.setage (110); User.setid (1); returnuserservice.updateuser (user); } @RequestMapping ("/getredisuser") PublicString Getredisuser () {returnUserservice.getuser (); }}
The controller layer injects the interface layer, directly invokes the logic of the service layer, and the processing logic of the program is placed in the service implementation layer. The controller only needs to accept parameters and handle simple conversion logic.
Focus: Design Restfule interface style (to be perfected)
Springboot Integrated MySQL and MyBatis