1.整合JDBC使用
1.创建项目
选择需要的依赖: web 和 mysql驱动
2.打开项目
在项目的配置文件中**(application.yml)**进行配置数据库信息
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql//localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
在url中要配置时区,字符编码。
**driver-class-name:**也和2之前的版本不同,之前的是com.mysql.cj.jdbc.Driver
3.使用我们的Idea连接我们的mysql数据库
1.
在test中,测试数据库连接
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws Exception{
/*查看获取的数据源*/
System.out.println(dataSource.getClass());
/*获取连接*/
Connection connection = dataSource.getConnection();
System.out.println(connection);
/*关闭连接*/
connection.close();
}
5.最后,测试是否可以查询数据
创建一个controller
JdbcTemplate里面已经注入了数据源和配置,所以我们注入JdbcTemplate即可。
敲重点!
这里我们没有实体类,那么我们的数据怎么获取?
我们可以使用 List<Map<String,Object>> 来封装我们的数据
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/hello")
public List<Map<String,Object>> jdbcQuery(){
String sql = "select * from customer";
List<Map<String, Object>> list_map = jdbcTemplate.queryForList(sql);
return list_map;
}
最后访问http://localhost:8080/hello即可。
敲重点!
我们可以查看jdbcTemplate源码,来看一下
6. 最后简单的实现增删改查
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/hello")
public List<Map<String,Object>> getUser(){
String sql = "select * from user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
@GetMapping("/addUser")
public String addUser(){
String sql = "insert into user(name,gender) values('鲁班大师','男')";
jdbcTemplate.update(sql);
return "update/ok";
}
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id){
String sql = "update user set name=?,gender=? where id = "+id;
Object[] objects = new Object[2];
objects[0] = "木兰";
objects[1] = "女";
jdbcTemplate.update(sql,objects);
return "update/ok";
}
@GetMapping("/delUser/{id}")
public String delUser(@PathVariable("id") int id){
String sql = "delete from user where id = "+id;
jdbcTemplate.update(sql);
return "del/ok";
}
2.整合Druid数据源
1.导入Druid依赖
https://mvnrepository.com/artifact/com.alibaba/druid
2.要使用Druid数据源,记得更改为Druid
在配置中更改
type: com.alibaba.druid.pool.DruidDataSource
3.我们来配置一些参数来测试一下:
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
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
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3.Druid强大的在于他可以配置东西
1.创建一个config包,下边创建DruidConfig.java进行配置
创建后,先在文件上加上 @Configuration
**敲重点!**因为这里使用了log4j,所以我们必须导入log4j的pom依赖
写完之后,一定要注入到Bean中
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
@Configuration
public class DruidConfig {
/*我们想要使用在配置文件中给Druid配置的属性,那么我们就要将这个方法和配置文件绑定到一起
* 所以要将这个方法交给Bean管理,并且添加配置文件 @ConfigurationProperties
* */
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
/*后台监控 : web.xml , ServletRegistrationBean*/
/*因为 SpringBoot 内置了 Servlet容器 所以没有web.xml 替代方法:ServletRegistrationBean*/
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean<Servlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
/*后台需要有人登录,账号密码配置*/
Map<String, String> initParameters = new HashMap<>();
/*增加配置*/
/*配置账号密码,账号密码的key值是固定不变的 loginUsername loginPassword*/
initParameters.put("loginUsername","admin");
initParameters.put("loginPassword","123");
/*允许访问*/
initParameters.put("allow","");
/*禁止访问 后边写IP地址*/
initParameters.put("kuangshen","192.168.11.123");
bean.setInitParameters(initParameters);
return bean;
}
/*配置一个过滤器 filter*/
@Bean
public FilterRegistrationBean filterFilterRegistrationBean(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
/*这个是阿里巴巴的过滤器*/
bean.setFilter(new WebStatFilter());
/*可以过滤那些请求呢?*/
Map<String, String> initParameters = new HashMap<>();
/* 这些东西不进行统计 ~~ map的key值 是我们在WebStatFilter过滤器中查看源码得到的*/
initParameters.put("exclusions","*.js,*.css,/druid/**");
bean.setInitParameters(initParameters);
return bean;
}
}
4.整合MyBatis
1.整合包
mybatis-spring-boot-start
这个包不是spring boot官方的
<!--mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2.写数据库配置,并测试
3.导入lombok依赖,写pojo类
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
Pojo.User类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String gender;
}
4.写mapper接口
mapper注解表明这是一个mapper类
也可以在主类上添加注解@MapperScan(“com.kuangshen.mapper”)来扫描mapper下的所有类
@Mapper/*这个注解表明了这是 mybatis 的mapper类*/
@Repository/*Dao层使用 @Repository 交给Spring */
public interface UserMapper {
/*查询所有用户*/
List<User> getAllUser();
/*查询单个用户*/
User getUserById(int id);
/*添加用户*/
void addUser(User user);
/*更改用户*/
void updateUser(User user);
/*删除用户*/
void deleteUser(int id);
}
5.mapper.xml文件放在resources目录下
在resources目录下创建mybatic -> mapper -> UserMapper.xml
**xml的配置信息可以在mybatis的中文文档中查找:**https://mybatis.org/mybatis-3/zh/getting-started.html
<?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.kuangshen.mapper.UserMapper">
</mapper>
首先!!先将namespace改成我们自己的映射文件
要在yml文件中添加配置我们的mapper文件的位置!!
# 整合mybatis
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.kuangshen.mapper
开始根据我们的mapper接口来写我们的mapper.xml文件
在插入的时候,传入的是类user,直接写name,id就可以,不需要user.id,否则会找不到
<?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.kuangshen.mapper.UserMapper">
<select id="getAllUser" resultType="com.kuangshen.pojo.User">
select * from user
</select>
<select id="getUserById" resultType="com.kuangshen.pojo.User">
select * from user where id = #{
id}
</select>
<insert id="addUser" parameterType="com.kuangshen.pojo.User">
insert into user(id,name,gender) values(#{
id},#{
name},#{
gender})
</insert>
<update id="updateUser" parameterType="com.kuangshen.pojo.User">
update user set name=#{
user.name} , gender=#{
user.gender} where id=#{
user.id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{
id}
</delete>
</mapper>
6.使用controller完成增删改查
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
/*查询所有用户*/
@GetMapping("/getAllUser")
public List<User> getAllUser(){
List<User> allUser = userMapper.getAllUser();
return allUser;
}
/*根据用户ID查询用户*/
@GetMapping("/getUserById/{id}")
public String getUserById(@PathVariable("id") int id){
userMapper.getUserById(id);
return "delete OK";
}
/*添加用户*/
@GetMapping("/addUser")
public String addUser(){
User user = new User();
user.setName("王五");
user.setGender("男");
user.setId(5);
userMapper.addUser(user);
return "add OK!";
}
/*更新用户*/
@GetMapping("/updateUser")
public String updateUser(){
return "update ok !";
}
/*删除用户*/
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id){
userMapper.deleteUser(id);
return "delete OK!";
}
}