如何使用接口和 JPA
首先我应该说,我对 Java EE 还很陌生,而且我在 Java 方面还没有很强的理论背景。
我无法掌握如何在 Java 中将 JPA
与 interfaces
一起使用。为了说明我发现的困难,我创建了一个非常简单的例子。
如果我有两个简单的接口 Person
和 Pet
:
public interface Person
{
public Pet getPet();
public void setPet(Pet pet);
}
public interface Pet
{
public String getName();
}
以及一个实现 Person
和 Person
的实体 PersonEntity
实现 Pet
的 code>PetEntity:
@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
方法中的情况,在该方法中我想要保留上述两个实体之间的关系?
我想使用接口的主要原因是因为我想保持模块/层之间对公共接口的依赖关系。我还能如何避免从例如我的 ManagedBean 直接获得实体的依赖关系?
如果有人建议不要在实体上使用接口,那么请解释有哪些替代方法或模式。
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.
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.
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();
}
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 */
}
How do I properly handle the case in the setPet
method in which I want to persist the relationships between the two entities above?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
targetEntity
关系注释中的属性。You can use
targetEntity
property in the relationship annotation.