如何使用接口和JPA [英] How to work with interfaces and JPA
问题描述
我应该首先说我是Java EE的新手,而且我还没有很强的Java理论背景。
I should start out by saying that I am fairly new to Java EE and that I do not have a strong theoretical background in Java yet.
我有麻烦如何在Java中使用 JPA
和 interfaces
。为了说明我发现的困难,我创建了一个非常简单的例子。
I'm having trouble grasping how to use JPA
together with interfaces
in Java. To illustrate what I find hard I created a very simple example.
如果我有两个简单的接口 Person
和宠物
:
If I have two simple interfaces Person
and Pet
:
public interface Person
{
public Pet getPet();
public void setPet(Pet pet);
}
public interface Pet
{
public String getName();
}
和实体 PersonEntity
实现 Person
以及实现 Pet
PetEntity >:
And an Entity PersonEntity
which implements Person
as well as a PetEntity
which implements Pet
:
@Entity
public class PersonEntity implements Person
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private PetEntity pet;
@Override
public void setPet(Pet pet)
{
/* How do i solve this? */
}
}
@Entity
public class PetEntity implements Pet
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
/* Getters and Setters omitted */
}
如何在 setPet
方法中正确处理案例,我想在其中保持上述两个实体之间的关系?
How do I properly handle the case in the setPet
method in which I want to persist the relationships between the two entities above?
我想使用接口的主要原因是因为我想保持模块/层之间的依赖关系到公共接口。我怎样才能避免从例如我的ManagedBean直接到实体?
The main reason I want to use interfaces is because I want to keep dependencies between modules/layers to the public interfaces. How else do I avoid getting a dependency from e.g. my ManagedBean directly to an Entity?
如果有人建议不要在实体上使用接口,请说明有哪些替代方法或模式。
If someone recommends against using interfaces on entities, then please explain what alternatives methods or patterns there are.
推荐答案
您可以使用 <关系注释中的code> targetEntity 属性。
You can use targetEntity
property in the relationship annotation.
@Entity
public class PersonEntity implements Person {
private Long id;
private Pet pet;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
@OneToOne(targetEntity = PetEntity.class)
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
}
这篇关于如何使用接口和JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!