SpringBoot+MyBatis+Mysql 详细示例

SpringBoot 与 MyBatis 整合,底层数据库为 mysql 的使用示例

 项目下载链接:https://github.com/DFX339/bootdemo.git

 

新建 maven 项目,web 项目,项目名为 bootdemo

  项目结构目录如下: 还有个 pom.xml 文件没有在截图里面

  项目需要编写的文件主要有: 

  项目启动类:  Application.java   ServletInitializer.java  

  前端控制器类:UserController.java 

  业务层的接口与实现类:UserIservice.java  UserService.java

  Mybatis 的接口: UserMapper.java 

  接口对应的 mapper 文件:UserMapper.xml

  实体类:User.java

  maven 项目的配置文件: pom.xml

 

 

(1)编写实体类 User.java

package smm.springboot_ftl.bean;

/**

  • User 实体类
  • @author Administrator

*/
public class User {

</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> String username;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> String password;
</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> age;

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> User(){}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> getId() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> id;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> setId(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.id =<span style="color: rgba(0, 0, 0, 1)"> id;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getUsername() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> username;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setUsername(String username) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.username =<span style="color: rgba(0, 0, 0, 1)"> username;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getPassword() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> password;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setPassword(String password) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.password =<span style="color: rgba(0, 0, 0, 1)"> password;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> getAge() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> age;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> setAge(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> age) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.age =<span style="color: rgba(0, 0, 0, 1)"> age;
}

}

 

(2)登录 mysql 数据库,新建数据库 springboot_mybatis(数据库名)

  新建表 user(表名),表的字段如图所示

 

 

(3)编写持久层接口:  UserMapper.java  (定义操作数据库的方法)  这里切记要用 @Mapper 注解标识

package smm.springboot_ftl.mapper;

import org.apache.ibatis.annotations.Mapper;

import smm.springboot_ftl.bean.User;

@Mapper
public interface UserMapper {

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> insert(User user);

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> update(User user);

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> delete(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id);

</span><span style="color: rgba(0, 0, 255, 1)">public</span> User find(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id);

}

 

(4)编写持久层接口对应的 mapper.xml 文件: UserMapper.xml  (编写增删改查对应的 sql 语句)

 存储位置: src/main/resources/mapper

<?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">  

<!-- 指定工作空间,要与接口名相同,源代码没有去看,猜测应该是通过 "这里的 namespace. 下边方法的 id" 来定位方法的 -->
<mapper namespace="smm.springboot_ftl.mapper.UserMapper">

&lt;!-- insert user --&gt;
&lt;insert id = "insert" parameterType="smm.springboot_ftl.bean.User"&gt;<span style="color: rgba(0, 0, 0, 1)">
    INSERT INTO USER(ID,USERNAME,PASSWORD,AGE) VALUES(#{id},#{username},#{password},#{age});
</span>&lt;/insert&gt;

&lt;!-- update user --&gt;
&lt;update id="update" parameterType="smm.springboot_ftl.bean.User"&gt;<span style="color: rgba(0, 0, 0, 1)">
    UPDATE USER SET USERNAME</span>=#{username} , PASSWORD=#{password} , AGE = #{age} WHERE ID=<span style="color: rgba(0, 0, 0, 1)">#{id}
</span>&lt;/update&gt;

&lt;!-- find user --&gt;
&lt;select id="find" parameterType="int" resultType="smm.springboot_ftl.bean.User"&gt;<span style="color: rgba(0, 0, 0, 1)">
    SELECT ID,USERNAME,PASSWORD,AGE FROM USER WHERE ID</span>=#{0<span style="color: rgba(0, 0, 0, 1)">}
</span>&lt;/select&gt;

&lt;!-- delete user --&gt;
&lt;delete id="delete" parameterType="int"&gt;<span style="color: rgba(0, 0, 0, 1)">
    DELETE FROM USER WHERE ID</span>=#{0<span style="color: rgba(0, 0, 0, 1)">}
</span>&lt;/delete&gt;

</mapper>

 

(5)编写业务层接口: UserIService.java

package smm.springboot_ftl.service;

import org.springframework.stereotype.Component;

import smm.springboot_ftl.bean.User;

public interface UserIService {

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> insert(User user);<br></span></pre>
    public void update(User user) ;

    public User find(int id);
  
    public void delete(int id);
}

 

(6)编写业务层接口的实现类:UserService.java (切记要使用 @Service("userService") 类标识类,表示这是 service)

@ComponentScan({"ssm.springboot_ftl.mapper"}):是为了找到对应的 UserMapper 对象
package smm.springboot_ftl.service;

import javax.annotation.Resource;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import smm.springboot_ftl.bean.User;
import smm.springboot_ftl.mapper.UserMapper;

@ComponentScan({"ssm.springboot_ftl.mapper"})
@Service(
"userService")
public class UserService implements UserIService{

@Resource
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> UserMapper userMapper;

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> insert(User user) {
    userMapper.insert(user);
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> update(User user) {
    userMapper.update(user);
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> User find(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> userMapper.find(id);
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> delete(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id){
    userMapper.delete(id);
}

}

 

(7)编写前端控制器类: UserController.java

@RestController 标识这个类,返回的结果为 Json 字符串。

@RestController 注解,相当于 @Controller+@ResponseBody 两个注解的结合,返回 json 数据不需要在方法前面加 @ResponseBody 注解了,但使用@RestController 这个注解,就不能返回 jsp,html 页面,视图解析器无法解析 jsp,html 页面

如果需要返回数据到 jsp 或者 html 页面,则使用 @Controller 注解。这里推荐使用 @Controller 注解,因为需要直接返回数据的时候可以增加 @ResponseBody 注解

@ComponentScan({"smm.springboot_ftl.service"}) :标识业务层的类,用来找到业务层对象,smm.springboot_ftl.service是业务类的路径

@MapperScan("smm.springboot_ftl.mapper") :标识持久层 mapper 接口,用来找到 mapper 对象, smm.springboot_ftl.mapper 是接口的路径

这三个注解都不能少!!! 少了 SpringBoot 就无法正常启动了!!

package smm.springboot_ftl.action;

import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import smm.springboot_ftl.bean.User;
import smm.springboot_ftl.service.UserService;
/**

  • 在定义一个 Rest 接口时,我们通常会使用 GET,POST,PUT,DELETE 几种方式来完成我们所需要进行 CRUD 的一些操作,

  • 我们在这里罗列和教大家在实际开发中的使用,一些基本概念我们就不再赘述,例如使用 POST 的优缺点,可使用参数的大小限制等地:

    GET:一般用于查询数据,不办函数据的更新以及插入操作。由于明文传输的关系,我们一般用来获取一些无关用户的信息。

    POST:一般用于数据的插入操作,也是使用最多的传输方式,但是在 H5 调用时会有跨域的问题,一般使用 JSONP 来解决。

    PUT:我们使用 PUT 方式来对数据进行更新操作。

    DELETE:用于数据删除,注意在数据库内是逻辑删除(改变数据状态,用户不再查询得到,但还保留在数据库内)还是物理删除(真删了)。

  • @author Administrator

*/
@RestController
@ComponentScan({
"smm.springboot_ftl.service"})
@MapperScan(
"smm.springboot_ftl.mapper")
public class UserController {

@Resource
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> UserService userService;

 @RequestMapping(</span>"/say"<span style="color: rgba(0, 0, 0, 1)">)  
 </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String say(){  </span>
     <span style="color: rgba(0, 0, 255, 1)">return</span> "springboot-a"+<span style="color: rgba(0, 0, 0, 1)">userService;
 }  

@RequestMapping(</span>"/find"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String find(){
    User user </span>=  userService.find(18<span style="color: rgba(0, 0, 0, 1)">);
    ModelAndView mav </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> ModelAndView();
    mav.addObject(</span>"user","sadf"<span style="color: rgba(0, 0, 0, 1)">);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "HelloWord"+"fasdf--"+user.getUsername()+"--"+<span style="color: rgba(0, 0, 0, 1)">user.getPassword();
}


@RequestMapping(</span>"/ajax"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String find1(){
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "[''message':'123dfx']"<span style="color: rgba(0, 0, 0, 1)">;
}

// public static void main(String[] args){
// SpringApplication.run(UserController.class,args);
// }
}

 

(8)ServletInitializer.java  这个类的主要内容如下:

package smm.springboot_ftl;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

@Override
</span><span style="color: rgba(0, 0, 255, 1)">protected</span><span style="color: rgba(0, 0, 0, 1)"> SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> application.sources(Application.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);
}

}

 

(9)SpringBoot 的配置文件: application.properties 文件内容如下:

 存储位置: src/main/resources

server.context-path : 配置访问该项目的项目路径,不配置时默认为 /  , 配置后必须加上项目名才能访问项目

server.context-path=/HelloWorld

spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.datasource.url
=jdbc:mysql://localhost:3306/springboot_mybatis
spring.datasource.username =root
spring.datasource.password
=root

mybatis.typeAliasesPackage=smm.springboot_ftl.bean
mybatis.mapperLocations
=classpath:/mapper/UserMapper.xml

Freemarker \u914D\u7F6E

\u6587\u4EF6\u914D\u7F6E\u8DEF\u5F84

spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.cache
=false
spring.freemarker.charset
=UTF-8
spring.freemarker.check
-template-location=true
spring.freemarker.content
-type=text/html
spring.freemarker.expose
-request-attributes=true
spring.freemarker.expose
-session-attributes=true
spring.freemarker.request
-context-attribute=request
spring.freemarker.suffix
=.ftl

 

(10)配置 maven 项目的配置文件,pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>smm</groupId>
    <artifactId>bootdemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>bootdemo Maven Webapp</name>
    <url>http://maven.apache.org</url>
&lt;parent&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
    &lt;version&gt;1.5.6.RELEASE&lt;/version&gt;
    &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
&lt;/parent&gt;

&lt;build&gt;
    &lt;finalName&gt;bootdemo&lt;/finalName&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;inherited&gt;<span style="color: rgba(0, 0, 255, 1)">true</span>&lt;/inherited&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
            &lt;version&gt;3.5.1&lt;/version&gt;
            &lt;configuration&gt;
                &lt;source&gt;${compiler.source}&lt;/source&gt;
                &lt;target&gt;${compiler.target}&lt;/target&gt;
                &lt;encoding&gt;${project.build.sourceEncoding}&lt;/encoding&gt;
                &lt;compilerArguments&gt;
                    &lt;extdirs&gt;${project.basedir}/src/main/webapp/WEB-INF/lib&lt;/extdirs&gt;
                &lt;/compilerArguments&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
        
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
&lt;properties&gt;
    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
    &lt;compiler.source&gt;1.7&lt;/compiler.source&gt;
    &lt;compiler.target&gt;1.7&lt;/compiler.target&gt;

    &lt;!-- servlet/jsp/EL (2.4/2.0/?)(2.5/2.1/2.1),(3.0/2.2/2.2),(3.1/2.3/3.0) --&gt;
    &lt;servlet.version&gt;3.1.0&lt;/servlet.version&gt;
    &lt;jsp.version&gt;2.3.1&lt;/jsp.version&gt;
    &lt;jstl.version&gt;1.2&lt;/jstl.version&gt;
    &lt;junit.version&gt;4.12&lt;/junit.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;${junit.version}&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
        &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
        &lt;version&gt;${servlet.version}&lt;/version&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
        &lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt;
        &lt;version&gt;${jsp.version}&lt;/version&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
        &lt;artifactId&gt;jstl&lt;/artifactId&gt;
        &lt;version&gt;${jstl.version}&lt;/version&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;org.objenesis&lt;/groupId&gt;
        &lt;artifactId&gt;objenesis&lt;/artifactId&gt;
        &lt;version&gt;1.2&lt;/version&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;
        &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;
        &lt;version&gt;1.2.0&lt;/version&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt;
        &lt;optional&gt;<span style="color: rgba(0, 0, 255, 1)">true</span>&lt;/optional&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
        &lt;version&gt;5.1.6&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
    &lt;/dependency&gt; 
&lt;!-- freemarker jar包导入 --&gt;   
   &lt;dependency&gt;  
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;  
        &lt;artifactId&gt;spring-boot-starter-freemarker&lt;/artifactId&gt;  
    &lt;/dependency&gt; 

&lt;/dependencies&gt;

</project>

 

 (11)启动项目,访问项目。

  进入 Application.java

  右击 --》  Run   As  --》  Java Application

  启动成功后,在浏览器通过 URL 访问:  http:// 当前 ip:8080/server.context-path 指定的值 /RequestMapping 对应的值

  例如: http://127.0.0.1:8080/HelloWorld/find

  访问结果如图所示:(注意,这里自己要往数据库中插入一条数据,id 为 UserController 类中 find 方法对应的 id)