参考: http://blog.csdn.net/saytime/article/details/74783296
spring boot可以使用全注解的方式进行开发,极大的提高了开发效率,为越来越多的公司所使用,
mybatis允许开发者使用sql语句,使开发更具灵活性。下面讲一下如何将spring boot 和mybatis整合起来
0:准备数据
CREATE TABLE `tb_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `username` varchar(50) NOT NULL COMMENT '用户名', `age` int(11) NOT NULL COMMENT '年龄', `ctm` datetime NOT NULL COMMENT '创建时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('张三', '18', NOW()) ; INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('李四', '20', NOW()) ;
1:首先创建maven工程,工程目录结构图如下:springBootDemo1
2:添加springboot 的工程依赖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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liyafei</groupId>
<artifactId>springBootDemo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<webVersion>3.1</webVersion>
<mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
</properties>
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <!-- Spring-Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <!-- Add typical dependencies for a web application --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> </dependencies> <build> <!-- 将工程打包成可执行jar文件 --> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
3: 为工程添加配置文件applIcation.yml
application.yml
spring: //数据源 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/demo username: root password: 1367356 mybatis: //配置mybatis mapper-locations: classpath:mybatis/mapper/*.xml Mapper所在的配置文件路径,进行扫描 config-location: classpath:mybatis/mybatis-config.xml mybaits-config文件 type-aliases-package: com.liyafei.dao.pojo <!-- pojo所在的包,与表一一对应-->
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="com.liyafei.dao.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.liyafei.dao.pojo.User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> <result column="ctm" property="ctm" jdbcType="TIMESTAMP"/> </resultMap> <sql id="Base_Column_List" > id, username, age, ctm </sql> <select id="getUserList" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM tb_user </select> <select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM tb_user WHERE id = #{id} </select> <insert id="add" parameterType="com.liyafei.dao.pojo.User" > INSERT INTO tb_user (username,age,ctm) VALUES (#{username}, #{age}, now()) </insert> <update id="update" parameterType="java.util.Map" > UPDATE tb_user SET username = #{user.username},age = #{user.age} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Integer" > DELETE FROM tb_user WHERE id = #{id} </delete> </mapper>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> </typeAliases> </configuration>
4:创建dao层类
public class User { private int id; private String username; private int age; private Date ctm; }
package com.liyafei.dao.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.liyafei.dao.pojo.User; @Repository public interface UserMapper { User getUserById(Integer id); public List<User> getUserList(); public int add(User user); public int update(@Param("id") Integer id, @Param("user") User user); public int delete(Integer id); }
5:创建service层
package com.liyafei.service; import java.util.List; import com.liyafei.dao.pojo.User; public interface UserService { User getUserById(Integer id); public List<User> getUserList(); public int add(User user); public int update(Integer id, User user); public int delete(Integer id); }
package com.liyafei.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.liyafei.dao.mapper.UserMapper; import com.liyafei.dao.pojo.User; @Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; public User getUserById(Integer id) { return userMapper.getUserById(id); } public List<User> getUserList() { return userMapper.getUserList(); } public int add(User user) { return userMapper.add(user); } public int update(Integer id, User user) { return userMapper.update(id, user); } public int delete(Integer id) { return userMapper.delete(id); } }
6:创建controller层
package com.liyafei.controller; import javax.websocket.server.PathParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.liyafei.dao.pojo.User; import com.liyafei.service.UserService; import com.liyafei.util.JsonResult; @RestController public class UserController { @Autowired private UserService userService; /** * ����ID��ѯ�û� * @param id * @return */ @RequestMapping(value = "user/{id}", method = RequestMethod.GET) public ResponseEntity<JsonResult> getUserById (@PathVariable(value="id") String id){ //@ResponseBody //public String getUserById (@PathVariable(value="id") String id){ System.out.println(id); JsonResult r = new JsonResult(); int id1=Integer.parseInt(id); try { User user = userService.getUserById(id1); r.setResult(user); r.setStatus("ok"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("error"); e.printStackTrace(); } //return "hello world"; return ResponseEntity.ok(r); } }
7:创建util工具类
package com.liyafei.util; public class JsonResult { private String status = null; private Object result = null; public JsonResult status(String status) { this.status = status; return this; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } }
8:创建主函数,主函数需位于根目录下,与其同级的包将会被扫描
package com.liyafei; 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; @EnableAutoConfiguration @SpringBootApplication @MapperScan("com.liyafei.dao.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
9:启动工程,进行测试,成功。