Spring Boot之Spring-Data-JPA

Spring Boot,记录一下库JPA,一上手的时候,看着spring的配置真也是头疼,各种数据库….之前我只了解Mysql或Oracle,结果你来这么多,不知道想干什么!

JPA是一个ORM的映射框架,目的就是为了提高开发效率和提升性能体验

添加JPA库包

1
2
3
4
5
6
7
8
9
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

application.yml中可以添加执行sql语句显示

1
2
3
4
5
6
7
8
spring:
datasource:
username: [username]
password: [password]
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true

添加JpaRepository关联数据库应用

添加数据库对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Entity(name = "test")
@Table(name = "test")
public class TestModel {

public String user;
public String title;
public String image;
public double price;
public String time;
public String region;

@Id
public String id;

// **必须**填写空构造函数
publicTestModel () {
}
}

关联Reposity

1
2
3
4
5
6
@Repository
public interface TestRepository extends JpaRepository<TestModel, String> {

@Query("select t.user, t.title, t.image, t.price, t.time, t.region from test t")
Page<TestModel> findTestList(Pageable pageable);
}

映射api接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController
@RequestMapping("/test")
public class TestController {

@Resource
private TestRepository repository;

@GetMapping("/list")
public Page<TestModel> list(
@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "6") Integer size
) {
Sort sort = Sort.by(Sort.Direction.DESC, "id");
PageRequest pageable = PageRequest.of(page, size, sort);
return repository.findAll(pageable);
}
}

添加完成后,就可以一键使用Spring Boot JPA套餐了,套餐丰富到你已经不用再写一条SQL语句了,如果实在要写,可以参考我上面写的findTestList示例(爬坑前方法!)

套餐示例,可以直接看JpaRepositoryPagingAndSortingRepositoryCrudRepository

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

Their main functions are:

  • CrudRepository mainly provides CRUD functions.
  • PagingAndSortingRepository provides methods to do pagination and sorting records.
  • JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don’t need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

总结就是JpaRepository功能强大,你只需要它,你还可以试试RxJava2CrudRepository等异步Repository

支持关键字模糊匹配

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is, Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull, Null findByAge(Is)Null … where x.age is null
IsNotNull, NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection ages) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

例如:

1
2
3
4
@Repository
public interface UserRepository extends CrudRepository<UserModel, Long> {
UserModel findByUser(String user);
}

其中user就是UserModel中的成员变量

错误org.springframework.data.mapping.PropertyReferenceException: No property id found for type [entity]

这里因为基类Model中没有id成员,不只是标记@Id,而是必须为id,如

1
2
@Id
public String id;

Navicat修改表结构

  1. 保存当前SQL数据:转存SQL文件->选择“结构和数据”
  2. 修改表结构:右键->设计表,再修改所需要的表
  3. 删除数据库,再重新导航SQL运行文件

参考

https://stackoverflow.com/questions/14014086/what-is-difference-between-crudrepository-and-jparepository-interfaces-in-spring
https://docs.spring.io/spring-data/jpa/docs/2.2.1.RELEASE/reference/html/#reference
https://spring.io/projects/spring-data-jpa#overview

文章作者: 二十I邊界
文章链接: https://xuie0000.com/post/2019-11-20-2019/Spring-Boot之Spring-Data-JPA.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 二十I邊界