假设我有两个相关的实体,例如帐户类型和帐户看起来像这样
//Accounts.java
@Entity
@Table(name = "accounts")
@XmlRootElement
public class Accounts implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "account_id")
private Long accountId;
@JoinColumn(name = "account_type_id", referencedColumnName = "account_type_id")
@ManyToOne(optional = false)
private AccountTypes accountTypeId;
@JoinColumn(name = "customer_id", referencedColumnName = "customer_id")
@ManyToOne(optional = false)
private CustomerInformation customerId;
//AccountTypes.java
@Entity
@Table(name = "account_types")
@XmlRootElement
public class AccountTypes implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "account_type_id")
private Integer accountTypeId;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "account_type_name")
private String accountTypeName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "accountTypeId")
private Collection<CustomerAccounts> customerAccountsCollection;
我希望能够
select from accounts where accounts.customerId=? and accountTypes.accountTypeName=?.
任何符合JPA标准的解决方案都适用于我,我只是不会运行两个不同的查询。
答案 0 :(得分:1)
我假设CustomerInformation
在customerId
类型中有Long
字段:
String hqlString = "select account from Accounts account where account.customerId.customerId=:customerId and account.accountTypeId.accountTypeName=:accountTypeName";
Query query = getSession().createQuery(hqlString);
query.setLong("customerId", customerId);
query.setString("accountTypeName", accountTypeName);
Accounts account = (Accounts) query.uniqueResult(); //if it's not unique then query.list()
我建议您将班级重命名为Account
和AccountType
。也不要像你一样用private CustomerInformation customerId;
来命名一个具有id的对象。你将看到如何编写搞砸的hql。
答案 1 :(得分:0)
您可以根据您创建的实体类使用以下查询。
select from Account acnt
where acnt.customerId=:customerId
and acnt.accountTypeId.accountTypeName = :accountTypeName
答案 2 :(得分:0)
感谢您的回答,但这对我有用 -
String hql_string = "from Accounts acnt where acnt.customerId.id=:custmerID and acnt.accountTypeId.accountTypeName=:typeName";
Query query = entityManager.createQuery(hql_string);
query.setParameter("custmerID", new Long(customer_id));
query.setParameter("typeName", "Account Type Name");
感谢#Mustafa,会更改变量名称。