
Spring boot + Mybatis 整合
Spring boot+Mybatis,相對于原來的Spring+SpringMVC+Mybatis簡單好多
一、java web開發(fā)環(huán)境搭建
參考教程:http://www.itdecent.cn/p/39dec5a0ab55
二、Spring boot搭建
1、Intellij idea菜單欄File->new->project

2、選擇左側(cè)欄中spring initializr,右側(cè)選擇jdk版本,以及默認(rèn)的Service URL,點(diǎn)擊next。

3、然后填寫項(xiàng)目的Group、Artifact等信息,helloworld階段選默認(rèn)就可以了,點(diǎn)擊next。

4、左側(cè)點(diǎn)擊Web選擇web,SQL選擇Mybatis、MYSQL(數(shù)據(jù)庫用的是mysql,大家可以選擇其他DB),點(diǎn)擊next。

5、填寫Project name 等信息,然后點(diǎn)擊Finish。

6、一個(gè)maven web項(xiàng)目就創(chuàng)建好了,目錄結(jié)構(gòu)如下:

Spring boot就搭建好了,pom.xml里已經(jīng)有了Spring boot的jar包,包括我們的mysql數(shù)據(jù)連接的jar包。Spring boot內(nèi)置了類似tomcat這樣的中間件,所以,只要運(yùn)行DemoApplication中的main方法就可以啟動(dòng)項(xiàng)目了。
在src/main/java下新建目錄com/demo/entity/User
package com.example.demo.entity;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
相同demo目錄下新建controller/TestBootController
package com.example.demo.controller;
import com.example.demo.entity.User;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/boot")
public class TestBootController {
@RequestMapping("/user")
public User getUser(){
User user = new User();
user.setName("boot_test");
return user;
}
}
Spring boot啟動(dòng)默認(rèn)是要加載數(shù)據(jù)源的,所以我們在src/main/resources下新建application.yml
數(shù)據(jù)庫使用的是mysql。可根據(jù)自己的需求更換數(shù)據(jù)庫
#默認(rèn)使用配置
spring:
profiles:
active: dev
#公共配置與profiles選擇無關(guān)
mybatis:
typeAliasesPackage: com.example.demo.entity
mapperLocations: classpath:mapper/*.xml
--- #分隔線不能少
#開發(fā)配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/test #數(shù)據(jù)庫地址+數(shù)據(jù)庫名字(自定義)
username: root #帳號(自定義)
password: root #密碼(自定義)
driver-class-name: com.mysql.jdbc.Driver #驅(qū)動(dòng)
將pom.xml中加載數(shù)據(jù)源的jar包先注釋掉也可以。
/*<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>*/
最終結(jié)構(gòu)springboot目錄如下
啟動(dòng)DemoApplication的main方法,訪問http://localhost:8080/boot/user即可
ps:如果自定義了包名等~復(fù)制代碼請注意修改對應(yīng)包名
三、整合Mybatis
1、集成druid,使用連接池。pom.xml中添加:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
最終的pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
到此Spring boot 就完成整合了~ 可以運(yùn)行測試下能否順利運(yùn)行。
2.用MyBatis Generator自動(dòng)生成代碼,或者自定義編寫各層
最終目錄請看文章最后
public class User {
private Integer id;
private String userName;
private String password;
private Integer age;
//省略get set方法...
}
public interface UserDao {
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
}
UserMapper.xml 中注意替換成自己的User對象地址 type 和parameterType
<?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.xc.dao.UserDao" ><!--修改自定義地址 -->
<resultMap id="BaseResultMap" type="com.xc.entity.User" ><!--修改自定義地址 -->
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, password, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user_t
where id = #{id,jdbcType=INTEGER}
</select>
<insert id="insertSelective" parameterType="com.xc.entity.User" ><!--修改自定義地址 -->
insert into user_t
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="password != null" >
password,
</if>
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
</mapper>
3.修改DemoApplication.java,添加掃描dao層接口。
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.dao") //修改成自己的dao地址
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4.添加Service/impl 和Controller層
public interface UserService {
public User getUserById(int userId);
boolean addUser(User record);
}
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
@Override
public boolean addUser(User record) {
boolean result = false;
try {
userDao.insertSelective(record);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
@RestController
@EnableAutoConfiguration
@RequestMapping("/boot")
public class TestBootController {
@Resource
private UserService userService;
@RequestMapping("/user")
@ResponseBody
public User getUser(HttpServletRequest request, Model model){
int userId = Integer.parseInt(request.getParameter("id"));
User user = this.userService.getUserById(userId);
return user;
}
}
5.Mysql創(chuàng)建測試表和插入數(shù)據(jù)
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
`id` int(11) NOT NULL DEFAULT '0',
`user_name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`age` int(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES ('0', 'bb', 'bb', '11');
INSERT INTO `user_t` VALUES ('1', 'aa', 'aaa', '11');
6.瀏覽器訪問http://localhost:8080/boot/user?id=1

7.最終項(xiàng)目結(jié)構(gòu)圖
