摘要:无。
环境
Windows 10 企业版 LTSC 21H2 MySQL 5.7.40 Java 1.8 Maven 3.6.3 Spring 5.3.31 Spring Boot 2.7.18
1 前期准备 1.1 准备数据 创建数据库表:
mysql 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 CREATE DATABASE IF NOT EXISTS test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;USE test; CREATE TABLE IF NOT EXISTS user ( id INT AUTO_INCREMENT PRIMARY KEY COMMENT '主键' , name VARCHAR (100 ) NOT NULL COMMENT '姓名' , age INT NOT NULL COMMENT '年龄' , email VARCHAR (100 ) DEFAULT NULL COMMENT '邮箱' ) ENGINE= InnoDB DEFAULT CHARSET= utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT= '用户表' ; INSERT INTO user (name, age, email) VALUES ('张三' , 18 , 'zhangsan@example.com' ), ('李四' , 20 , 'lisi@example.com' ), ('王五' , 28 , 'wangwu@example.com' );
1.2 创建项目 目录结构:
code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 demo-spring-data-jpa/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── example/ │ │ │ ├── entity/ │ │ │ │ └── User.java │ │ │ ├── repository/ │ │ │ │ └── UserRepository.java │ │ │ └── DemoApplication.java │ │ └── resources/ │ │ └── application.yml │ └── test/ └── pom.xml
1.3 管理依赖 创建pom.xml文件:
pom.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <?xml version="1.0" encoding="UTF-8" ?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.7.18</version > <relativePath /> </parent > <groupId > com.example</groupId > <artifactId > demo-spring-data-jpa</artifactId > <version > 1.0.0-SNAPSHOT</version > <properties > <java.version > 1.8</java.version > </properties > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-jpa</artifactId > </dependency > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <optional > true</optional > </dependency > <dependency > <groupId > com.mysql</groupId > <artifactId > mysql-connector-j</artifactId > <version > 8.3.0</version > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > </plugin > </plugins > </build > </project >
1.4 配置文件 创建application.yml文件:
application.yml 1 2 3 4 5 6 7 8 9 10 11 12 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useSSL=false&connectionTimeZone=Asia/Shanghai username: root password: 123456 jpa: show-sql: true hibernate: ddl-auto: none
1.5 编写代码 创建User类并映射到user表:
java 1 2 3 4 5 6 7 8 9 10 11 12 13 @Data @NoArgsConstructor @AllArgsConstructor @Entity @Table public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private Integer age; private String email; }
2 基于Repository使用 2.1 入门案例 创建UserRepository接口,继承JpaRepository接口,在运行时会自动生成实现类:
java 1 2 public interface UserRepository extends JpaRepository <User, Integer> {}
在启动类中实现CommandLineRunner接口,在应用启动后测试:
java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 @SpringBootApplication public class DemoApplication implements CommandLineRunner { @Autowired private UserRepository userRepository; public static void main (String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run (String... args) { userRepository.save(new User (null , "张三" , 18 , "zhangsan@example.com" )); userRepository.deleteById(2 ); userRepository.save(new User (1 , "李四" , 30 , "lisi@example.com" )); User findUser = userRepository.findById(1 ).orElse(null ); System.out.println("查询用户:" ); System.out.println(findUser); List<User> findUserList = userRepository.findAll(); System.out.println("查询所有用户:" ); findUserList.forEach(System.out::println); Page<User> page = userRepository.findAll(PageRequest.of(0 , 5 , Sort.by("age" ).descending())); System.out.println("分页查询用户:" ); page.getContent().forEach(System.out::println); System.out.println("总记录数:" + page.getTotalElements()); System.out.println("总页数:" + page.getTotalPages()); System.out.println("是否存在下一页:" + page.hasNext()); } }
2.2 方法名查询 支持根据方法名自动生成查询语句:
java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public interface UserRepository extends JpaRepository <User, Integer> { List<User> findByName (String name) ; List<User> findByNameLike (String name) ; List<User> findByNameContaining (String name) ; List<User> findByAgeBetween (Integer minAge, Integer maxAge) ; List<User> findByOrderByAgeDesc () ; List<User> findByEmailIsNull () ; }
常用的方法名关键字:
按条件查询 :findBy。
模糊匹配 :Like、Containing、StartingWith、EndingWith。
范围查询 :Between。
排序 :OrderBy。
排序顺序 :Asc、Desc。
空值判断 :IsNull、IsNotNull。
组合条件 :And、Or。
使用方法名查询:
java 1 2 3 4 5 6 System.out.println(userRepository.findByName("张三" )); System.out.println(userRepository.findByNameLike("%张%" )); System.out.println(userRepository.findByNameContaining("张" )); System.out.println(userRepository.findByAgeBetween(20 , 30 )); System.out.println(userRepository.findByOrderByAgeDesc()); System.out.println(userRepository.findByEmailIsNull());
2.3 自定义查询 使用@Query注解可以自定义查询语句:
java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public interface UserRepository extends JpaRepository <User, Integer> { @Query(value = "SELECT * FROM user WHERE id = :id", nativeQuery = true) User findByIdFunc (@Param("id") Integer id) ; @Query("SELECT u FROM User u WHERE u.id = :id") User findByIdDirect (@Param("id") Integer id) ; @Modifying @Transactional @Query("UPDATE User u SET u.age = :age WHERE u.id = :id") int updateByIdDirect (@Param("id") Integer id, @Param("age") Integer age) ; @Modifying @Transactional @Query("DELETE FROM User u WHERE u.id = :id") int deleteByIdDirect (@Param("id") Integer id) ; }
使用自定义查询:
java 1 2 3 4 System.out.println(userRepository.findByIdFunc(1 )); System.out.println(userRepository.findByIdDirect(1 )); System.out.println(userRepository.updateByIdDirect(1 , 20 )); System.out.println(userRepository.deleteByIdDirect(1 ));
条