Spring Boot之集成Jdbc Template、MyBatis、Spring Data JPA
一、Spring Boot集成Jdbc Template
官方文档:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html
1.引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.添加application.properties配置
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3.接口及其实现
public interface UserService {
public void insertUser();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void insertUser() {
jdbcTemplate.update("insert into user values(null,?,?);","小白",20);
}
}
4.执行测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class Test {
@Autowired
private UserService userService;
@org.junit.Test
public void test(){
userService.insertUser("小白",20);
}
}
二、Spring Boot集成MyBatis
1.引入依赖
<!--mybatis集成依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.2</version>
</dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.配置数据源
在application.properties中加入如下配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
3.加入MyBatis配置
在application.properties中加入如下配置:
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:cn/ybzy/mapper/*Mapper.xml
#pojo别名扫描包
mybatis.type-aliases-package=cn.ybzy.model
4.创建Mapper接口
使用注解标注,2选其一
1.接口上需要加上@Mapper注解,标注该接口属于MyBatis接口
2.在启动类 or 配置类添加@MapperScan(basePackages = "cn.ybyz.mapper") 指定包扫描
1.使用xml方式
使用xml方式需要在application.yml中进行mybatis的配置,需要结合第3点与第5点
@Mapper
public interface UserMapper {
List<User> getAll();
}
2.使用注解方式
简单的语句只需要使用@Insert、@Update、@Delete、@Select
这4个注解即可,动态SQL语句需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider
等注解。
具体可参考MyBatis官方文档:https://mybatis.org/mybatis-3/
@Mapper
public interface UserMapper {
@Insert("insert into user(tb_name,tb_sex) values(#{name},#{sex})")
int add(User user);
@Update("update user set tb_name=#{name},tb_sex=#{sex} where id=#{id}")
int update(User user);
@Delete("delete from user where id=#{id}")
int deleteById(String id);
@Select("select * from user where id=#{id}")
@Results(id = "user",value= {
@Result(property = "id", column = "id", javaType = Long.class),
@Result(property = "name", column = "tb_name", javaType = String.class),
@Result(property = "sex", column = "tb_sex", javaType = String.class)
})
Student queryUserById(String id);
}
5.配置Mapper映射文件
在src\main\resources\mapper
路径下加入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.ybzy.mapper.UserMapper" >
<!--查询所有-->
<select id="getAll" resultType="user">
select * from user
</select>
</mapper>
6.引导类加上包扫描
@SpringBootApplication
@MapperScan(basePackages = "cn.ybyz.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
7.创建UserController
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = "/getAllUser")
public Object getAllUser(){
List<User> userList = userMapper.getAll();
return userList;
}
}
8.执行测试
9.集成mybatis-pagehelper分页插件
原理:在查询前使用分页插件,统一拦截sql,为其提供分页功能
添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
配置yml
# 分页插件配置
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
分页数据封装对象
public class PageResult {
// 当前页数
private int page;
// 总页数
private int total;
// 总记录数
private long records;
// 每页显示的内容
private List<?> rows;
}
使用分页插件
将查询数据封装到分页数据封装对象并返回
/**
* page: 第几页
* pageSize: 每页显示条数
*/
PageHelper.startPage(page, pageSize);
List<User> list = UserMapper.getAll();
PageInfo<?> pageInfo = new PageInfo<>(list);
PageResult pageResult = new PageResult();
pageResult.setPage(page);
pageResult.setRows(list);
pageResult.setTotal(pageInfo.getPages());
pageResult.setRecords(pageInfo.getTotal());
return pageResult;
三、Spring Boot集成Spring Data JPA
1.添加依赖
<!-- springBoot JPA起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.配置数据库
#MYSQL配置:
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
3.配置Jpa
#JPA配置:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
4.创建实体并配置实体
@Entity(name = "tb_user"))
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String name;
}
5.编写UserRepository
public interface UserRepository extends JpaRepository<User,Long>{
public List<User> getAll();
}
6.执行测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application .class)
public class JpaTest {
@Autowired
private UserRepository userRepository;
@Test
public void test() {
List<User> userList = userRepository.getAll();
for (User user : userList) {
System.out.println("user = " + user);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137029.html