1-2、SpringBoot 整合 Mybatis 的示例
2017-05-31 本文已影响187人
xinput
最近一直公司代码框架由hibernate切换到mybatis,springboot以及cloud如火如荼,所以写了这篇文章用于记录。
项目工具:idea + maven + mysql
一、创建数据库和数据表
1、创建数据库 test_mybatis
CREATE DATABASE test_mybatis;
2、创建表 user
CREATE TABLE `user` (
`user_id` INT(11) NOT NULL COMMENT '主键',
`user_name` VARCHAR(64) NOT NULL COMMENT '姓名',
`address` VARCHAR(256) NULL DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`user_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
3、插入数据
insert into user(user_id,user_name,address) values(1,"小明","北京市朝阳区望京");
insert into user(user_id,user_name,address) values(2,"小红","北京市东城区东直门");
insert into user(user_id,user_name,address) values(3,"小绿","北京市西城区车公庄");
二、项目代码
1、创建一个springboot项目。修改pom文件,完整文件如下:
<?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.xinput</groupId>
<artifactId>springbootMybatisXml</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- Spring Boot 启动父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<properties>
<mysql.version>5.1.39</mysql.version>
</properties>
<dependencies>
<!-- Spring Boot Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- MySQL 连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、创建实体类 User
package com.xinput.entity;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 8296061679272038443L;
private Long userId;
private String userName;
private String address;
// get set方法
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", address='" + address + '\'' +
'}';
}
}
3、创建dao接口文件
package com.xinput.dao;
import com.xinput.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
int insertUser(User userEntity);
User selectByPrimaryKey(Long userId);
User selectByName(String userName);
}
4、创建dao和entity对应的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.xinput.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.xinput.entity.User">
<id column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="user_name" property="userName" jdbcType="VARCHAR"/>
<result column="address" property="address" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
user_id,user_name,address
</sql>
<!--================测试用:生成user===================-->
<insert id="insertUser" parameterType="com.xinput.entity.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userId != null">user_id,</if>
<if test="userName != null">user_name,</if>
<if test="address != null">address,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userId != null">#{userId,jdbcType=INTEGER},</if>
<if test="userName != null">#{userName,jdbcType=VARCHAR},</if>
<if test="address != null">#{address,jdbcType=VARCHAR},</if>
</trim>
</insert>
<!--================根据主键查商户===================-->
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long">
select
<include refid="Base_Column_List"/>
from user
where user_id = #{userId,jdbcType=CHAR}
</select>
<!--================根据name查商户===================-->
<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select
<include refid="Base_Column_List"/>
from user
where user_name = #{userName,jdbcType=CHAR}
</select>
</mapper>
5、创建service类,spring中,其实可以不用写接口,可以直接写service类
//服务类
package com.xinput.service;
import com.xinput.dao.UserMapper;
import com.xinput.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User getUserById(Long userId) {
return userMapper.selectByPrimaryKey(userId);
}
}
6、修改appilcation.properties文件配置
#嵌入tomcat默认端口
server.port=8081
#mysql属性
spring.datasource.url=jdbc:mysql://192.168.99.100:3306/test_mybatis? useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
#mybatis
# 为实体对象所在的包,跟数据库表一一对应
mybatis.typeAliasesPackage=com.xinput.entity
# typeAliasesPackage: com.xinput.**.mapper
# mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
注释:
mybatis 其他配置相关详解如下:
mybatis.config = mybatis 配置文件名称
mybatis.mapperLocations = mapper xml 文件地址
mybatis.typeAliasesPackage = 实体类包路径
mybatis.typeHandlersPackage = type handlers 处理器包路径
mybatis.check-config-location = 检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
mybatis.executorType = 执行模式。默认是 SIMPLE3.在 Application 应用启动类添加注解 MapperScan
7、controller类代码
package com.xinput.controller;
import com.xinput.entity.User;
import com.xinput.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value="/user/{id}",method= RequestMethod.GET)
public User findUser(@PathVariable("id")Long id){
User user = userService.getUserById(id);
return user;
}
}
8、修改Application.java启动类代码
package com.xinput;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages="com.xinput.dao")
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
三、启动 Application
访问 http://localhost:8081/user/1。
如果大家觉得还有什么问题,可以给我留言,我看到会回复的。