JBoss EAP 6
hibernate 4
我有一个带有 Web 浏览器客户端的 J2EE 应用程序。 ( Apache 点击) 内部业务逻辑和客户端都使用相同的实体对象。
我想将实体中的所有关系设置为延迟加载。这样我就有了很好的表现。
但是当在客户端使用实体时(即 apache click 的服务器端代码),我需要大量的关系来预先加载。客户端代码通过 session bean 访问后端。
所以我有几种方法可以解决这个问题:
为每个 JPA 实体创建 2 个,一个使用预加载,一个使用延迟加载。然后在客户端使用预加载的,在服务端使用延迟加载的。大多数服务器逻辑都在一个事务中,所以延迟加载在这里很好。
使所有关系延迟加载。从客户端访问实体时,请确保存在事务。 ( @TransactionAttribute(TransactionAttributeType.REQUIRED) ) 并对必要字段的访问进行编码,以便在 session bean 调用后可以访问它们。 但这意味着我必须在不需要时开始交易,即如果我只得到一些对象。而且我必须维护更多代码。而且我必须确切地知道客户需要什么样的关系。
创建一个继承层次结构,其中我有一个 super 实体,然后是 2 个子实体,一个具有延迟加载的对象关系,一个只有值,没有对象。即:
super 好
@MappedSuperclass
public class SuperOrder {
@Id
@Column(name = "id")
@GeneratedValue(.....)
private Long id;
@Column(name = "invoice", length = 100)
private String invoice;
child 1
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "testorder")
@SequenceGenerator(....)
public class Order extends SuperOrder {
@ManyToOne(targetEntity = PrintCustomerEnt.class, fetch = FetchType.EAGER, optional = true)
@JoinColumn(name = "print_customer_id", nullable = true)
@ForeignKey(name = "fk_print_customer")
@Valid
private PrintCustomerEnt printCustomer;
public PrintCustomerEnt getPrintCustomer() {
return printCustomer;
}
public void setPrintCustomer(final PrintCustomerEnt printCustomer) {
this.printCustomer = printCustomer;
}
}
child 2
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "testorder")
@SequenceGenerator(...)
public class LazyOrder extends SuperOrder {
@Transient
private String printCustomerName;
@Column(name = "print_customer_id", nullable = true)
private Long printCustomerId;
什么是最佳实践...或者是否有其他好的方法来做到这一点。
基本上问题是我想在不同的场景中使用相同的实体。有时我需要预加载,有时我需要延迟加载。
最佳答案
我建议您只创建一个具有惰性关系的 JPA 实体,当您需要急切加载时,其中一些创建一个使用 JPQL(HQL) 的服务做一些 FETCH 技巧。这个想法是一个 JPA 实体和许多服务。
关于java - JPA - Eager - Lazy 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21715490/