JBoss EAP 6
Hibernate 4
我有一个Web浏览器客户端的J2EE应用程序。在内部业务逻辑和客户端中都使用相同的实体对象。
我希望将实体中的所有关系设置为延迟加载,以获得良好的性能。
但是当在客户端(即 Apache click 的服务器端代码)中使用这些实体时,我需要许多关系被急切地加载。客户端通过会话bean访问后端。
所以我有几种解决方法:
创建两个JPA实体,一个具有急切加载,一个具有延迟加载。然后在客户端中使用具有急切加载的实体,在服务器端使用具有延迟加载的实体。大部分服务器逻辑都在事务中,因此延迟加载在此处很好。
使所有关系都延迟加载。当从客户端访问实体时,请确保存在事务。(@TransactionAttribute(TransactionAttributeType.REQUIRED))并编写对必要字段的访问代码,以便在会话bean调用后可以访问它们。但这意味着我必须在不需要时启动事务,即如果我只获取一些对象。并且我必须维护更多代码。还必须确切地知道客户端需要哪些关系。
创建一个继承层次结构,其中我有一个超级实体,然后有两个子实体,一个具有对象关系的延迟加载,另一个只有值,没有对象。例如:
Super
@MappedSuperclass
public class SuperOrder {
@Id
@Column(name = "id")
@GeneratedValue(.....)
private Long id;
@Column(name = "invoice", length = 100)
private String invoice;
子元素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;
}
}
子元素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;
什么是最佳实践...或者说还有其他好的方法可以解决这个问题。
基本上问题是我想在不同场景下使用相同的实体。有时候我需要急切加载,有时候我需要延迟加载。