目录
1.导入相关依赖
2.配置数据源和MyBatis
3. MyBatis Generator 自动生成代码
4. MyBatis注解版
5.事务管理
1.导入相关依赖
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.korb1n</groupId>
<artifactId>springboot_project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_project</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- JDBC-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MYSQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<resources>
<!-- 编译时扫描所有的xml文件资源-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/mybatis/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.配置数据源和MyBatis
在使用数据库之前,我们首先需要配置好数据源,这里采用阿里巴巴的Druid
连接池。
application.yml:
server:
port: 8081
#输出日志到项目根目录下的log/spring.log文件中
logging:
file:
path: log
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/personal_community?useUnicode=true&&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置Druid数据源监控
#配置监控统计拦截的filters,stat-监控统计、log4j-日志记录、wall-防御sql注入
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
#扫描pojo包,给包下所有pojo对象起别名,不配置需要在xml中输入全类名,配置了可直接输入类名
type-aliases-package: cn.korb1n.springbootproject.pojo
#xxxMapper.xml与同名接口不在同一目录,需要指定xml的位置;在同一目录则不需要该配置
#mapper-locations: classpath:mybatis/mapper/*.xml
Druid 提供了数据源监控的功能,并提供了一个Web界面供用户查看,所以在上述配置文件中进行了相关配置,并且还需要对该页面进行servlet视图配置。
DruidConfig:
package cn.korb1n.springbootproject.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
//读取配置文件中的druid的配置
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//Druid数据源监控
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//配置参数
Map<String,String> initParameter = new HashMap<>();
//设置登录账号密码
initParameter.put("loginUsername","admin");
initParameter.put("loginPassword","123456");
//允许谁能访问
initParameter.put("allow","");
bean.setInitParameters(initParameter);
return bean;
}
}
最后一步还需要扫描Mapper接口,注入到Spring容器中。有两种方式,第一种是在每一个Mapper接口上添加@Mapper
注解和@Repository
注解;
例如UserMapper:
package cn.korb1n.springbootproject.mapper;
package cn.korb1n.springbootproject.mapper;
import cn.korb1n.springbootproject.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface UserMapper {
User selectByPrimaryKey(Integer id);
}
另一种方式则是批量扫描所有的Mapper,在主启动类上添加@MapperScan
注解,然后每个Mapper只需要添加@Repository
注解即可,实际上@Repository
注解都可以不用添加,添加上是为了避免IDEA识别不到在@Autowired
时报红。
SpringbootProjectApplication :
package cn.korb1n.springbootproject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication()
@MapperScan(value = "cn.korb1n.springbootproject.mapper")
public class SpringbootProjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootProjectApplication.class, args);
}
}
3. Mybatis Generator 自动生成代码
配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/mybatis/generator/generatorConfig.xml
,可在上述pom.xml中查看。
编辑 generatorConfig.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="D:\apache-maven-repository\mysql\mysql-connector-java\8.0.21\mysql-connector-java-8.0.21.jar"/>
<context id="content" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/personal_community?serverTimezone=GMT%2B8" userId="root" password="root">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="cn.korb1n.springbootproject.pojo" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<!-- 这里没有将xml放到与接口同目录,一般配置文件还是放resources中;
注意在application.yml中配置mybatis的mapper-locations属性-->
<sqlMapGenerator targetPackage="mybaits.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.korb1n.springbootproject.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
点击IDEA的run->Edit Configurations
,然后添加配置,如下图:
双击运行即可:
生成对应的pojo实体类、Mapper接口和同名xml SQL配置文件:
User.java(使用lombok插件构建):
package cn.korb1n.springbootproject.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.sql.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String telephone;
private String password;
private String nickname;
private Date birthday;
private Integer gender;
private String email;
private Integer type;
private String headUrl;
private Date createTime;
}
UserMapper.java:
package cn.korb1n.springbootproject.mapper;
import cn.korb1n.springbootproject.pojo.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
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="cn.korb1n.springbootproject.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="cn.korb1n.springbootproject.pojo.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="telephone" property="telephone" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="nickname" property="nickname" jdbcType="VARCHAR" />
<result column="birthday" property="birthday" jdbcType="DATE" />
<result column="gender" property="gender" jdbcType="INTEGER" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="type" property="type" jdbcType="INTEGER" />
<result column="headUrl" property="headUrl" jdbcType="VARCHAR" />
<result column="createTime" property="createTime" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="Base_Column_List" >
id, telephone, password, nickname, birthday, gender, email, type, headUrl, createTime
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="cn.korb1n.springbootproject.pojo.User" >
insert into user (id, telephone, password,
nickname, birthday, gender,
email, type, headUrl,
createTime)
values (#{id,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{nickname,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, #{gender,jdbcType=INTEGER},
#{email,jdbcType=VARCHAR}, #{type,jdbcType=INTEGER}, #{headurl,jdbcType=VARCHAR},
#{createtime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="cn.korb1n.springbootproject.pojo.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="telephone != null" >
telephone,
</if>
<if test="password != null" >
password,
</if>
<if test="nickname != null" >
nickname,
</if>
<if test="birthday != null" >
birthday,
</if>
<if test="gender != null" >
gender,
</if>
<if test="email != null" >
email,
</if>
<if test="type != null" >
type,
</if>
<if test="headurl != null" >
headUrl,
</if>
<if test="createtime != null" >
createTime,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="telephone != null" >
#{telephone,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="nickname != null" >
#{nickname,jdbcType=VARCHAR},
</if>
<if test="birthday != null" >
#{birthday,jdbcType=DATE},
</if>
<if test="gender != null" >
#{gender,jdbcType=INTEGER},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="type != null" >
#{type,jdbcType=INTEGER},
</if>
<if test="headurl != null" >
#{headurl,jdbcType=VARCHAR},
</if>
<if test="createtime != null" >
#{createtime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="cn.korb1n.springbootproject.pojo.User" >
update user
<set >
<if test="telephone != null" >
telephone = #{telephone,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="nickname != null" >
nickname = #{nickname,jdbcType=VARCHAR},
</if>
<if test="birthday != null" >
birthday = #{birthday,jdbcType=DATE},
</if>
<if test="gender != null" >
gender = #{gender,jdbcType=INTEGER},
</if>
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="type != null" >
type = #{type,jdbcType=INTEGER},
</if>
<if test="headurl != null" >
headUrl = #{headurl,jdbcType=VARCHAR},
</if>
<if test="createtime != null" >
createTime = #{createtime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="cn.korb1n.springbootproject.pojo.User" >
update user
set telephone = #{telephone,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
nickname = #{nickname,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=DATE},
gender = #{gender,jdbcType=INTEGER},
email = #{email,jdbcType=VARCHAR},
type = #{type,jdbcType=INTEGER},
headUrl = #{headurl,jdbcType=VARCHAR},
createTime = #{createtime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
4. MyBatis注解版
虽然xml中写SQL可以最大程度上解耦,灵活性更强,但如果你觉得写xml或者在接口和xml之间跳转时麻烦,也可以使用Mybatis的注解版。
使用注解来写SQL语句相较于在xml中简介非常多:
/**
* User映射类
* Created by Administrator on 2017/11/24.
*/
@Mapper//在启动类中配置了@MapperScan则可以不用写
@Repository
public interface UserMapper {
@Select("SELECT * FROM T_USER WHERE PHONE = #{phone}")
User findUserByPhone(@Param("phone") String phone);
@Insert("INSERT INTO T_USER(NAME, PASSWORD, PHONE) VALUES(#{name}, #{password}, #{phone})")
int insert(@Param("name") String name, @Param("password") String password, @Param("phone") String phone);
}
如果想了解更多Mybatis的注解使用,推荐参考该篇博文:https://blog.csdn.net/winter_chen001/article/details/78623700 。
5.事务管理
在操作数据库对数据进行读写操作过程中,为了保证数据的安全性和稳定性,事务管理非常重要,在SpringBoot中为我们提供了事务管理的方式,使用@Transactional
注解即可,详细使用方法请参考我的另一篇博文:SpringBoot通过@Transactional管理事务 。