JPA JOIN实现简单访问



我希望能够使用外键包含另一个表中的@Entity。我正在遵循指南,但我仍然很困惑,似乎无法做到这一点。最终目标是这样的:

@Entity
@Table(name = "Labor", schema = "dbo", catalog = "database")
public class LaborEntity {
private int laborId;
private Timestamp laborDate;
private Integer jobNumber;
private Integer customerId;
//mapping of customer to labor
private CustomerEntity customer;
@Id
@Column(name = "LaborID", nullable = false)
public int getLaborId() {
return laborId;
}
public void setLaborId(int laborId) {
this.laborId = laborId;
}
@Basic
@Column(name = "LaborDate", nullable = true)
public Timestamp getLaborDate() {
return laborDate;
}
public void setLaborDate(Timestamp laborDate) {
this.laborDate = laborDate;
}
@Basic
@Column(name = "JobNumber", nullable = true)
public Integer getJobNumber() {
return jobNumber;
}
public void setJobNumber(Integer jobNumber) {
this.jobNumber = jobNumber;
}
@Basic
@Column(name = "CustomerID", nullable = true)
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
@ManyToOne(targetEntity = CustomerEntity.class)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "CustomerID",                //in this table
referencedColumnName = "CustomerID",    //from CustomerEntity
insertable = false, updatable = false,
foreignKey = @javax.persistence.ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
public CustomerEntity getCustomer() {
return this.customer;
}
public void setCustomer(CustomerEntity customer) {
this.customer = customer;
}

无论如何,最终目标是从Customer表中获取Customer数据,作为Labor实体的一部分,这样就可以使用类似getCustomerEntity()的东西直接访问它。我想我必须首先使用这样的JOIN进行查询来完成它:

TypedQuery<LaborEntity> query = entityManager.createQuery(
"SELECT l FROM LaborEntity l " +
"INNER JOIN CustomerEntity c " +
"ON l.customerId = c.customerId " +
"WHERE l.laborDate = '" + date + "'", LaborEntity.class);
List<LaborEntity> resultList = query.getResultList();

然后我可以简单地访问相关联的客户,如下所示:

resultList.get(0).getCustomer().getCustomerName();

我是在做梦还是真的有可能?

是的,这是完全可能的。(不过,我不确定问题是什么,但假设你只想让它发挥作用(

  1. 查询需要是JPQL,而不是SQL。JPQL:上的Join不同

    "SELECT l FROM LaborEntity l " +
    "JOIN l.customer c " +
    "WHERE ... "
    

联接从根实体开始,然后使用字段名(而不是列(。您也可以使用JOIN FETCH,然后关联的实体(客户(将加载到同一查询中。(即获取EAGER(

其他建议:

  • 不要像date那样连接参数。请改用setParameter
  • 你不需要那些@Basic
  • 你不需要targetEntity = CustomerEntity.class。它将被自动检测到

最新更新