springboot_整合JDBC_Druid数据源_MyBatis
Springboot-JDBC
- 配置文件
#serverTimezone=GMT:设置时区
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
- 数据库使用,增删改查,Controller
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
//没有实体类,数据库中的东西,怎么获取?
@GetMapping("/userList")
public List<Map<String,Object>> userList(){
String sql = "select * from springboot_mybatis.user";
List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
return list_maps;
}
@GetMapping("/addUser")
public String addUser(){
String sql = "insert into springboot_mybatis.user(id,userName,passWord,realName) values (3,'DJ','123456','DingJie')";
jdbcTemplate.update(sql);
return "Update_OK";
}
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id")Integer id){
String sql = "update springboot_mybatis.user set userName=?,passWord=? where id = "+id;
//数据封装
Object[] objects = new Object[2];
objects[0] = "小明";
objects[1] = "11111";
jdbcTemplate.update(sql,objects);
return "Update_OK";
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id")Integer id){
String sql = "delete from springboot_mybatis.user where id = ?";
jdbcTemplate.update(sql,id);
return "Delete_OK";
}
}
注意:
springboot 2.3.7版本使用IDEA创建项目时,勾选了有关数据库的选项
springboot会自动在生成的properties文件中添加配置模板的信息:
# 应用名称
spring.application.name=springboot-04-data
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/blue?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=***
spring.datasource.password=***
# 应用服务 WEB 访问端口
server.port=8080
如果使用yaml文件进行配置,会导致数据库连接的失败,建议使用yaml,干掉properties。
02. Springboot-druid数据源
- druid数据源依赖
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
- log4j依赖
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
- druid数据元配置文件
spring:
datasource:
username: root
password: 123456
# url: jdbc:mysql://localhost:3306/springboot_mybatis?serverTimezone=GMT&useUnicode=true&characterEncoding=utf8&useSSL=false
# 失去问题
url: jdbc:mysql://localhost:3306/springboot_mybatis?serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#springboot 默认是不注入这些属性值的,需要自己绑定
#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
#配置监控统计拦截器filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入log4j依赖即可,Maven
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
userGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- druid的使用
新建DruidConfig
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控:web.xml
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//后台需要有人登录,账号密码配置
HashMap<String, String> initParameters = new HashMap<>();
//增加配置,登录的key是固定的不可以改变:loginUsername,loginPassword
initParameters.put("loginUsername","admin");
initParameters.put("loginPassword","123456");
//允许谁可以访问
initParameters.put("allow","");
//禁止谁能访问:initParameters.put("DingJie","127.0.0.1");
initParameters.put("DingJie","127.0.0.1");
registrationBean.setInitParameters(initParameters);
return registrationBean;
}
//filter 过滤器
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new WebStatFilter());
//可以过滤什么请求
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("exclusions","*.js,*.css,/druid/*");
registrationBean.setInitParameters(initParameters);
return registrationBean;
}
}
后台监控页面
03. Springboot-mybatis
- 3.1 加入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
- 3.2 创建User实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String userName;
private String passWord;
private String realName;
}
- 3.3 创建新的Mapper接口
//这个注解表示了这是一个mybatis的mapper类
@Mapper
@Repository
public interface UserMapper {
List<User> queryUserList();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
- 3.4 在resource下创建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="edu.dj.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from springboot_mybatis.user
</select>
<select id="queryUserById" resultType="User">
select * from springboot_mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="User">
insert into springboot_mybatis.user(id, userName, passWord, realName) VALUES (#{id},#{userName},#{passWord},#{realName})
</insert>
<update id="updateUser" parameterType="User">
update springboot_mybatis.user set userName=#{userName},realName=#{realName} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from springboot_mybatis.user where id = #{id}
</delete>
</mapper>
- 3.5 properties中配置整合mybatis(关键)
#整合mybatis(关键)
mybatis.type-aliases-package=edu.dj.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
- 3.6 controller中进行业务逻辑编写和测试
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
//查询所有
@GetMapping("/queryUserList")
public List<User> queryUserList(){
List<User> users = userMapper.queryUserList();
for (User user : users){
System.out.println(user);
}
return users;
}
//按ID查询
@GetMapping("/queryUserById/{id}")
public User queryUserById(@PathVariable("id")Integer id){
User user = userMapper.queryUserById(id);
return user;
}
//添加用户
@GetMapping("/addUser")
public String addUser(){
userMapper.addUser(new User(4,"cbg","1234567","曹保国"));
return "ADD_OK";
}
//修改用户
@GetMapping("/updateUser")
public String updateUser(){
userMapper.updateUser(new User(4,"cbg","1234567","曹保国12138"));
return "UPDATE_OK";
}
//根据id删除用户
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id")Integer id){
userMapper.deleteUser(id);
return "DELETE_OK";
}
}