4. 整合数据库
4.1 整合 JDBC
(1) 导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
(2) 配置数据库
spring:
datasource:
username: root
password: 981030
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
(3) 测试数据链接
@Test
void contextLoads() throws SQLException {
System.out.println("dataSource ==> " + dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println("connection ==> " + connection);
connection.close();
}
(4) RCUD
@RestController
public class JdbcController {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/userList")
public List<Map<String, Object>> userList() {
String sql = "select * from user";
List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
return list_maps;
}
@GetMapping("/addUser")
public String addUser() {
String sql = "insert into mybatis.user (id, name, pw) values (5, '周五', '555555')";
int add = jdbcTemplate.update(sql);
return "add ==> " + add;
}
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id) {
String sql = "update mybatis.user set name = ?, pw = ? where id = " + id;
Object[] objects = new Object[2];
objects[0] = "周武";
objects[1] = "50005";
int update = jdbcTemplate.update(sql, objects);
return "update ==> " + update;
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id) {
String sql = "delete from mybatis.user where id =? ";
int delete = jdbcTemplate.update(sql, id);
return "delete ==> " + delete;
}
}
4.2 整合 Druid
(1) 导入依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.21version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
(2) 配置数据源
spring:
datasource:
username: root
password: 981030
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
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, wall, log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
(3) 配置后台监控
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties("spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", "admin");
initParameters.put("loginPassword", "123456");
initParameters.put("allow", "");
bean.setInitParameters(initParameters);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("exclusions", "*.js, *.css, /druid/*");
bean.setInitParameters(initParameters);
return bean;
}
}
4.3 整合 Mybatis
(1) 配置 mapper 路径
# 整合 mybatis
mybatis.type-aliases-package=com.why.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
(2) 编写 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) 编写 xml 文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.why.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from user
select>
<select id="queryUserById" resultType="User">
select * from user where id = #{id}
select>
<insert id="addUser" parameterType="User">
insert into user (id, name, pw) values (#{id}, #{name}, #{pw})
insert>
<insert id="updateUser" parameterType="User">
update user set name = #{name}, pw = #{pw} where id = #{id}
insert>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
delete>
mapper>
(4) 编写控制器
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/queryUserList")
public List<User> queryUserList() {
List<User> userList = userMapper.queryUserList();
for (User user : userList) {
System.out.println("user ==> " + user);
}
return userList;
}
@GetMapping("/queryUserById/{id}")
public User queryUserById(@PathVariable("id") int id) {
User user = userMapper.queryUserById(id);
return user;
}
@GetMapping("/addUser")
public String queryUserById() {
int i = userMapper.addUser(new User(6, "吴六", "6000"));
return "添加 ==> " + i;
}
@GetMapping("/updateUser")
public String updateUser() {
int i = userMapper.updateUser(new User(6, "吴柳", "6000"));
return "更新 ==> " + i;
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id) {
int i = userMapper.deleteUser(id);
return "删除 ==> " + i;
}
}