和后端同学对接时,想起了自己对于springboot整合mybatis的方式忘得差不多了,因此将思路重新整理,做个记录。
springboot整合jdbc
首先新建项目,添加如上依赖;
然后新建yml文件配置连接数据库,
springboot默认自动配置了,因此可以去测试类直接进行测试:
package com.lk.springbootdatajdbc;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
@Autowired(required = false)
DataSource dataSource;
@Test
void contextLoads() {
try {
//看一下默认数据源
System.out.println(dataSource.getClass());
//获得连接
Connection connection = null;
connection = dataSource.getConnection();
System.out.println(connection);
//关闭连接
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
可以看到默认的数据源是 class com.zaxxer.hikari.HikariDataSource,HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat、jdbc 等连接池更加优秀;
然后新建controller,使用jdbcTemplate测试CRUD:
package com.lk.springbootdatajdbc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
@Autowired(required = false)
JdbcTemplate jdbcTemplate;
//查询employee表中所有数据
// List 中的1个 Map 对应数据库的 1行数据
// Map 中的 key 对应数据库的字段名,value 对应数据库的字段值
@GetMapping("/getuserlist")
public List
增加用户:
查看数据库发现添加成功;
删除成功后也确实同步到数据库,至此,springboot集成jdbc完成;
首先导入依赖:
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
然后根据新建实体类User,新建UserMapper接口,UserMapper.xml映射文件,然后编写UserController类进行测试,启动项目,访问即可:
#指定myBatis的核心配置文件与Mapper映射文件 mybatis.mapper-locations=classpath:mapper/*.xml # 注意:对应实体类的路径 mybatis.type-aliases-package=com.lk.springbootdatajdbc.pojo spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=liukang123.456.
@Mapper
//表示本类是一个mybatis的mapper
@Repository
public interface UserMapper {
List getUsers();
User getUser(int id);
}
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
//查询全部部门
@GetMapping("/getUsers")
public List getUsers(){
return userMapper.getUsers();
}
@GetMapping("/getUser/{id}")
public User getUser(@PathVariable("id") int id){
return userMapper.getUser(id);
}
}
查询成功,springboot整合mybatis成功,最重要的就是记住将mybatis的核心配置项在properties里注册即可。
此处我用的是xml方式进行映射,同时还有另一种方式,采用纯注解的方式:
@Select
@Insert
@Update
@Delete
此项目后端同学就是采用这种方式:
将所有的sql都写在java配置类的方法的注解上面,不需要使用xml,看起来更加直观,但是对于大型项目,我认为xml的方式,一个xml文件包含了所有的sql语句以及映射关系,出了问题比较容易查找。



