Question

Assuming I have two Entities that are related e.g. AccountTypes and Accounts that looks something like this

//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;

I want to be able to

select from accounts where accounts.customerId=? and accountTypes.accountTypeName=?. 

Any JPA compliant solution will work for me, I'd just rather not run two different queries.

No correct solution

OTHER TIPS

I am assuming CustomerInformation has customerId field in Long type:

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()

I suggest you to rename your classes into Account and AccountType. Also don't name an object with id like you did private CustomerInformation customerId; You will see how screwed hql is written.

You can use following query as per the your entity class you have created..

select from Account acnt
where acnt.customerId=:customerId
and acnt.accountTypeId.accountTypeName = :accountTypeName

Thanks for your answers but this is what worked for me -

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");

And thanks #Mustafa, would change the variables names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top