目录
ORMHibernate,JPA和SpringDataJpaJPA入门案列JPA的API介绍getOne和findOne的比较JPQL的基本使用specification的基本使用example的基本使用
多表设计
表之间的划分 分析步骤 多表设计(一对多) 多表设计(一对多)
对象导航查询 ★
对象导航查询
对象图导航检索方式是根据已经加载的对象,导航到他的关联对象。它利用类与类之间的关系来检索对象。例如:我们通过ID查询方式查出一个客户,可以调用Customer类中的getLinkMans()方法来获取该客户的所有联系人。对象导航查询的使用要求是:两个对象之间必须存在关联关系。
延迟加载的方式
@Test
@Transactional(rollbackFor
= Exception
.class)
public void testObjectQuery(){
Customer customer
=this.customerRepository
.getOne(31L
);
Set
<LinkMan> linkMans
= customer
.getLinkMans();
linkMans
.forEach(value
-> System
.out
.println(value
));
}
输出
LinkMan
{lkmId
=4, lkmName
='小李', lkmGender
='null', lkmPhone
='null', lkmMobile
='null', lkmEmail
='null', lkmPosition
='null', lkmMemo
='null'}
立即加载的方式
@Test
@Transactional(rollbackFor
= Exception
.class)
public void testObjectQueryByFindOne(){
Optional
<Customer> oCustomer
= this.customerRepository
.findOne((root
, query
, criteriaBuilder
) -> {
Path
<Object> custId
= root
.get("custId");
Predicate predicate
= criteriaBuilder
.equal(custId
, 31L
);
return predicate
;
});
Customer customer
= oCustomer
.get();
Set
<LinkMan> linkMans
= customer
.getLinkMans();
linkMans
.forEach(value
-> System
.out
.println(value
));
}
配置关联对象的加载方式,默认是LAZY
输出
LinkMan
{lkmId
=4, lkmName
='小李', lkmGender
='null', lkmPhone
='null', lkmMobile
='null', lkmEmail
='null', lkmPosition
='null', lkmMemo
='null'}
FetchType有两个实例对象LAZY和EAGER
从多的一方查询
@Test
@Transactional(rollbackFor
= Exception
.class)
public void testObjectQueryByGetOne2(){
LinkMan linkman
= this.linkManRepository
.getOne(4L
);
Customer customer
= linkman
.getCustomer();
System
.out
.println(customer
);
}
输出
Customer
{custId
=31, custName
='百度', custSource
='null', custIndustry
='null', custLevel
='null', custAddress
='null', custPhone
='null', linkMans
=[LinkMan
{lkmId
=4, lkmName
='小李', lkmGender
='null', lkmPhone
='null', lkmMobile
='null', lkmEmail
='null', lkmPosition
='null', lkmMemo
='null'}]}