我有两个类,如:
@Entity
public class Customer{
@Id
private String id;
private String name;
@Column(nullable=false, unique=true)
private String refId;
}
@Entity
public class Account{
@Id
private String id;
@Column(nullable=false, unique=true)
private String accountNr;
@Column(nullable=false)
private String accountType;
@Column(nullable=false, unique=true)
private String refId;
}
我想在refId上加入这两个类,以便对Account字段进行排序,例如:
select c.* from Customer as c inner join Account as a on a.refId=c.refId orderBy a.accountType
是否有办法在条件
Hibernate通常不允许您像在SQL查询中那样通过Criteria
执行"按需"连接。然而,使用具有多个标准的变通方法,这似乎确实是可能的。
但是如果你按照Alex的建议在你的Entity
类中映射一个关联,你可以像这样创建一个简单得多的Criteria
,因为Customer
将有一个account
对象已经"映射"到它:
Criteria criteria = session.createCriteria(Customer.class)
.createCriteria("account")
.addOrder(Order.asc("accountType"));
要进行关联,在Entity
类中,您可以用相关对象替换refId
字段。因此,在Customer
类中,您可以有一个Account
对象关联,如下所示(反之亦然):
@Entity
public class Customer {
// Instead of "refId" field:
@OneToOne(mappedBy = "customer")
private Account account;
}
@Entity
public class Account {
// Instead of "refId" field:
@OneToOne
@JoinColumn(name = "refIdColName")
private Customer customer;
}
假设这是一对一的关系。您不需要在一对一映射中引用主键。
您应该使用表之间的关系,例如@OneToOne
, @ManyToOne
。
之后就很容易写HQL
了。