Spring数据JPA中getReference方法的替代方法 [英] Alternatives to getReference method in Spring data JPA
问题描述
我发现自己在Spring Data JPA中难以实现可自定义的方法.
例如,我有一个Pet类,它有一个Owner(一对多).如果我有一个save(Pet pet, int ownerId)
的方法,该怎么办.如何获得ownerId
?使用Hibernate,我只能getReference
这样
I found myself struggling to implement customizable methods in Spring Data JPA.
For example, I have a Pet class, which has an Owner(Many to One rel.) What if I have a method to save(Pet pet, int ownerId)
. How can I get ownerId
? Using Hibernate I just can getReference
like that
public Pet save(Pet pet, int ownerId) {
if (!pet.isNew() && get(pet.getId(), ownerId) == null) {
return null;
}
pet.setUser(em.getReference(Owner.class, ownerId));
if (pet.isNew()) {
em.persist(pet);
return pet;
} else {
return em.merge(pet);
}
}
但是使用Spring DJPA并不是那么容易.我创建了扩展JpaRepository < Pet, Integer >
的接口,希望父类具有一个称为
saveWithReference
,但我什么也没找到..有什么主意吗?
But using a Spring DJPA it's not so easy. I've created an interface that extends JpaRepository < Pet, Integer >
, hoping that the parent class has a method called
saveWithReference
, but i didn't find anything.. Any ideas guys?
推荐答案
您应该同时具有PetRepository
和OwnerRepository
都扩展了JpaRepository
.
You should have both a PetRepository
and OwnerRepository
both extending JpaRepository
.
public interface PetRepository extends JpaRepository<Pet, Long> {}
和
public interface OwnerRepository extends JpaRepository<Owner, Long> {}
Using Spring Data JPA you can use the getOne
method to get a reference, this in contrast to the findOne
which will actually query the database.
使用EntityManager
编写的代码基本相同,应将其放在服务方法中,而不要直接使用EntityManager
,请使用2个存储库.
The code you wrote using the EntityManager
is basically the same and you should put that in a service method and instead of directly using the EntityManager
use the 2 repositories.
@Service
@Transactional
public PetService {
private final PetRepository pets;
private final OwnerRepository owners;
public PetService(PetRepository pets, OwnerRepository owners) {
this.pets=pets;
this.owners=owners;
}
public Pet savePet(Pet pet, long ownerId) {
if (!pet.isNew() && get(pet.getId(), ownerId) == null) {
return null;
}
pet.setUser(owners.getOne(ownerId));
return pets.save(pet);
}
}
类似的事情应该可以解决.无需在存储库中实现方法.
Something like that should do the trick. NO need to implement methods in your repository.
这篇关于Spring数据JPA中getReference方法的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!