如何使用接口和JPA

编程入门 行业动态 更新时间:2024-10-24 08:31:09
本文介绍了如何使用接口和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 :

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.

推荐答案

您可以使用 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

本文发布于:2023-11-04 05:35:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   接口   JPA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!