關于自動生成mapper文件,可通過筆者的另一篇文章《SpringBoot使用mybatis generator自動生成代碼》查看
文章目錄
1、項目結(jié)構(gòu)
2、數(shù)據(jù)庫結(jié)構(gòu)
3、依賴
4、yml配置
5、源碼
6、mapper文件
7、效果
8、druid的簡單實用
9、參考
1、項目結(jié)構(gòu)

2、數(shù)據(jù)庫結(jié)構(gòu)

3、依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
4、yml配置
關于yml文件
application-dev.yml:開發(fā)環(huán)境
application-test.yml:測試環(huán)境
application-prod.yml:生產(chǎn)環(huán)境
至于哪個具體的配置文件會被加載,需要在application.yml文件中通過spring.profiles.active屬性來設置,其值對應{profile}值。
application.yml
spring:
profiles:
active: dev
application-dev.yml
server:
port: 8080
spring:
datasource:
#mysql驅(qū)動
driver-class-name: com.mysql.jdbc.Driver
#基本屬性
url: jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC&allowMultiQueries=true
username: root
password: root
#druid相關配置
druid:
#監(jiān)控統(tǒng)計攔截的filters
# filter: stat
#配置初始化大小/最小/最大
initial-size: 1
min-idle: 1
max-active: 20
#獲取連接等待超時時間
max-wait: 60000
#間隔多久進行一次檢測,檢測需要關閉的空閑連接
time-between-eviction-runs-millis: 60000
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
# type-aliases-package: com.shufeng.hellomybatis.entity
#showSql
logging:
level:
com:
example:
mapper : debug
要注意修改為自己數(shù)據(jù)庫的名稱、賬戶及密碼
5、源碼
User.java
public class User {
private Integer id;
private String userName;
private String password;
private Integer age;
// 省略getter和setter
}
UserDao.java
import org.apache.ibatis.annotations.Mapper;
import com.shufeng.hellomybatis.entity.User;
@Mapper
public interface UserDao {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
可在UserDao 添加@Mapper或者在Application添加@MapperScan("com.shufeng.hellomybatis.dao"),從而使 UserDao 與后續(xù)的UserMapper.xml匹配。
但僅需使用一種。
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@MapperScan("com.shufeng.hellomybatis.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
UserService.java
import com.shufeng.hellomybatis.entity.User;
public interface UserService {
public User getUserById(int userId);
boolean addUser(User record);
}
UserServiceImpl.java
import org.springframework.stereotype.Service;
import com.shufeng.hellomybatis.dao.UserDao;
import com.shufeng.hellomybatis.entity.User;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements UserService
{
@Resource
private UserDao userDao;
public User getUserById(int userId)
{
return userDao.selectByPrimaryKey(userId);
}
public boolean addUser(User record)
{
boolean result = false;
try
{
userDao.insertSelective(record);
result = true;
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
UserController.java
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.shufeng.hellomybatis.entity.User;
import com.shufeng.hellomybatis.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/showUser")
@ResponseBody
public User toIndex(HttpServletRequest request, Model model){
int userId = Integer.parseInt(request.getParameter("id"));
User user = this.userService.getUserById(userId);
return user;
}
}
6、mapper文件

注意:
1、UserMapper.xml 文件的位置要與yml配置文件的位置
mapper-locations: classpath:mapper/*Mapper.xml一致
2、UserMapper.xml 文件中的namespace和type的值要改為與自己項目相同
<?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.shufeng.hellomybatis.dao.UserDao" >
<resultMap id="BaseResultMap" type="com.shufeng.hellomybatis.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>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user_t
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.shufeng.hellomybatis.entity.User" >
insert into user_t (id, user_name, password,
age)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.shufeng.hellomybatis.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>
<update id="updateByPrimaryKeySelective" parameterType="com.shufeng.hellomybatis.entity.User" >
update user_t
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.shufeng.hellomybatis.entity.User" >
update user_t
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
7、效果
瀏覽器訪問 http://localhost:8080/user/showUser?id=1

8、druid的簡單實用
可通過druid方便的監(jiān)控服務器性能,從而進行調(diào)優(yōu)。
添加配置DruidConfig.java
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean druidServlet() { // 主要實現(xiàn)WEB監(jiān)控的配置處理
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 進行druid監(jiān)控的配置處理操作
servletRegistrationBean.addInitParameter("allow",
"127.0.0.1,192.168.1.159"); // 白名單
servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名單
servletRegistrationBean.addInitParameter("loginUsername", "stat"); // 用戶名
servletRegistrationBean.addInitParameter("loginPassword", "Wkt_sTat_1031"); // 密碼
servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置數(shù)據(jù)源
return servletRegistrationBean ;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*"); // 所有請求進行監(jiān)控處理
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
return filterRegistrationBean ;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
訪問 http://localhost:8080/druid
賬號、密碼在配置文件中

可方便的查看各種性能指標,這里不做展開。

9、參考
spring boot+mybatis整合
SpringBoot整合Mybatis完整詳細版
單手擼了個springboot+mybatis+druid