这里主要说两种方式来连接MySQL。
添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
application.properties配置文件中增加数据库参数,信息内容如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/zdb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
调用
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Map<String, Object>> getDbType(){
String sql = "select * from t_user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
}
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
application.properties配置文件中增加数据库参数,信息内容如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/zbi_source
spring.datasource.username=root
spring.datasource.password=HNxhkjedu!@#07
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
如果你的项目需求相对简单,对代码的可读性和维护性要求较高,可以选择注解方式;
如果你的项目需求比较复杂,对动态SQL的需求较多,或者你更倾向于将数据访问逻辑与Java代码分离的方式,可以选择XML配置方式。
添加@Mapper
和@Repository
注解,这样就不用在Application中配置扫描的包了。
UserMapper.java
package cn.psvmc.zapicall.mapper;
import cn.psvmc.zapicall.bean.UserModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
@Select("SELECT id, name, age, sex FROM t_user")
List<UserModel> selectAll();
@Select("SELECT id, name, age, sex FROM t_user WHERE id = #{id}")
UserModel findById(@Param("id") String id);
}
不配置注解,在Application中添加扫描的包。
UserMapper.java
package cn.psvmc.zapicall.mapper;
import cn.psvmc.zapicall.bean.UserModel;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("SELECT id, name, age, sex FROM t_user")
List<UserModel> selectAll();
@Select("SELECT id, name, age, sex FROM t_user WHERE id = #{id}")
UserModel findById(@Param("id") String id);
}
Application上要添加注解
@MapperScan("cn.psvmc.zapicall.mapper")
简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,动态SQL语句需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。
具体可参考MyBatis官方文档:https://mybatis.org/mybatis-3/zh_CN/java-api.html。
@Select("select * from t_user where id=#{id}")
@Results(id = "student",value= {
@Result(property = "id", column = "id", javaType = Integer.class),
@Result(property = "name", column = "name", javaType = String.class),
@Result(property = "sex", column = "sex", javaType = Integer.class)
})
Student queryStudentById(String id);
在 MyBatis 中使用注解的方式编写 Mapper ,您可以通过使用 @SelectProvider
注解来添加判断条件。
@SelectProvider
注解允许您指定一个 Provider 类,该类包含根据不同条件生成 SQL 语句的方法。
首先,创建一个 Provider 类,它包含生成 SQL 语句的方法。方法的参数可以接受不同的参数,根据这些参数生成不同的 SQL 语句。
这里以生成一个包含条件判断的查询语句为例:
public class UserProvider {
public static String getQueryWithCondition(String condition) {
return "SELECT * FROM my_table WHERE " + condition;
}
}
然后,在 Mapper 接口的方法上使用 @SelectProvider
注解,并指定 Provider 类和方法:
public interface UserMapper {
@SelectProvider(type = UserProvider.class, method = "getQueryWithCondition")
List<MyEntity> findDataWithCondition(@Param("condition") String condition);
}
在上面的例子中,@Param("condition")
注解将方法参数 condition
映射到 SQL 语句中的 #{condition}
。
现在,您可以在调用 Mapper 方法时传入不同的条件,以根据条件生成不同的 SQL 语句:
List<MyEntity> result = myMapper.findDataWithCondition("id = #{id}");
注意
在编写动态 SQL 语句时,使用XML方式的时候可以使用 MyBatis 提供的条件判断标签,如
<if>
、<choose>
等,以动态生成不同的查询条件。 但在注解方式下,无法直接使用这些标签,需要通过自定义 Provider 方法来实现判断条件的拼装。
application.properties中添加配置
mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
mybatis.type-aliases-package=cn.psvmc.zapicall.bean
UserMapper.java
package cn.psvmc.zapicall.mapper;
import cn.psvmc.zapicall.bean.UserModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
List<UserModel> selectAll();
UserModel findById(@Param("id") String id);
}
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.psvmc.zapicall.mapper.UserMapper">
<resultMap id="UserMap" type="cn.psvmc.zapicall.bean.UserModel">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
<result column="sex" property="sex" jdbcType="INTEGER"/>
</resultMap>
<select id="selectAll" resultMap="UserMap">
select id,
name,
age,
sex
from t_user
order by id asc
</select>
<select id="findById" resultMap="UserMap" parameterType="java.lang.String">
SELECT id, name, age, sex FROM t_user WHERE id = #{id}
</select>
</mapper>
mybatis.type-aliases-package
配置后我们的实体类的包名就可以省略了
上面的可以简写为:
<?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.psvmc.zapicall.mapper.UserMapper">
<resultMap id="UserMap" type="UserModel">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
<result column="sex" property="sex" jdbcType="INTEGER"/>
</resultMap>
<select id="selectAll" resultMap="UserMap">
select id,
name,
age,
sex
from t_user
order by id asc
</select>
<select id="findById" resultMap="UserMap" parameterType="java.lang.String">
SELECT id, name, age, sex FROM t_user WHERE id = #{id}
</select>
</mapper>
在MyBatis中,jdbcType用于定义数据库和Java类型之间的映射关系。
它是通过XML映射文件或注解来配置的。
jdbcType的值可以是以下之一:
<?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.psvmc.zapicall.mapper.UserMapper">
<resultMap type="cn.psvmc.zapicall.bean.UserModel" id="UserMap">
<result property="id" column="id" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="age" column="age" jdbcType="INTEGER"/>
<result column="sex" property="sex" jdbcType="INTEGER"/>
</resultMap>
<!--查询单个-->
<select id="queryById" resultMap="UserMap">
select
id, name, age
from t_user
where id = #{id}
</select>
<!--查询指定行数据-->
<select id="queryAllByLimit" resultMap="UserMap">
select
id, name, age
from t_user
limit #{offset}, #{limit}
</select>
<!--通过实体作为筛选条件查询-->
<select id="queryAll" resultMap="UserMap">
select
id, name, age
from t_user
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>
<!--新增所有列-->
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into t_user(name, age)
values (#{name}, #{age})
</insert>
<!--通过主键修改数据-->
<update id="update">
update t_user
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
where id = #{id}
</update>
<!--通过主键删除-->
<delete id="deleteById">
delete from t_user where id = #{id}
</delete>
</mapper>
为了方便开发我们可以安装插件MyBatisX
package cn.psvmc.zapicall.bean;
public class UserModel {
private int id;
private String name;
private int age;
private int sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
UserService.java
package cn.psvmc.zapicall.service;
import cn.psvmc.zapicall.bean.UserModel;
import cn.psvmc.zapicall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired(required = false)
private UserMapper userMapper;
public List<UserModel> getUsers(){
return userMapper.selectAll();
}
public UserModel findById(String id){
return userMapper.findById(id);
}
}
package cn.psvmc.zapicall.controller;
import cn.psvmc.zapicall.bean.UserModel;
import cn.psvmc.zapicall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService service;
@RequestMapping("/list")
public List<UserModel> getUsers() {
List<UserModel> list = service.getUsers();
return list;
}
@RequestMapping("/userById")
public UserModel userById(@RequestParam("id")String id) {
return service.findById(id);
}
}
启动Maven项目,通过浏览器访问,地址如下:
http://localhost:8080/user/list
http://localhost:8080/user/userById?id=6
Druid不但提供连接池的功能,还提供监控功能,可以实时查看数据库连接池和SQL查询的工作情况。
<!-- druid数据源驱动 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
配置从
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/zbi_source?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
改为
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/zbi_source?useUnicode=true&characterEncoding=utf8
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
# 连接池配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
# 连接等待超时时间
spring.datasource.druid.max-wait=30000
# 配置检测可以关闭的空闲连接间隔时间
spring.datasource.druid.time-between-eviction-runs-millis=60000
# 配置连接在池中的最小生存时间
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=select '1' from dual
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-open-prepared-statements=20
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
# 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
spring.datasource.druid.filters=stat,wall
# Spring监控AOP切入点,如cn.psvmc.service.*,配置多个英文逗号分隔
#spring.datasource.druid.aop-patterns:
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions='*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=druid
spring.datasource.druid.stat-view-servlet.login-password=druid
spring.datasource.druid.filter.stat.log-slow-sql=true
访问
http://localhost:8080/druid/login.html
输入上面配置的账号密码druid
即可。
HikariCP
的性能和并发性。如果有 HikariCP
,SpringBoot 会选择它。Tomcat数据源连接池
可用,也可以使用它。HikariCP
和 Tomcat数据源连接池
都不可用,并且如果 Commons DBCP2
可用,就使用它。可以使用 spring.datasource.type
属性来指定要使用的连接池。
如果使用 spring-boot-starter-jdbc
或 spring-boot-starter-data-jpa
,将自动获得对 HikariCP
的依赖。