If Any field value of @EmbeddedId is null, which problem will arise?

Viewed 5323

I am fetching a problem with Hibernate @EmbeddedId. Code of my @EmbeddedId is:

@Embeddable
public class EnrolRegEmbededId implements Serializable
{
 @Column(name="ENROL_NO")
private String enrolNo;
@Column(name="REG_NO")
private String regNo;
}

My entity class is :

@Entity
@Table(name = "PTAX_ENROL_REG_PRINCIPAL_INFO")
public class Enrol_reg_principal_info implements Serializable {

@EmbeddedId
private EnrolRegEmbededId enrolReg;
@Column(name = "APPLN_TYPE")
private String type;
@Column(name = "FIRST_NM")
private String f_name;
@Column(name = "MIDDLE_NM")
private String m_name;
@Column(name = "LAST_NM")
}

Problem is : I get data from 'Enrol_reg_principal_info' class when both enrolNo and regNo have value. But get NUllPointerException when either enrolNo or regNo have value.

The hql is : String hql = " from Enrol_reg_principal_info prin where prin.enrolReg.regNo=:id"; for get value for regNo.

String hql = " from Enrol_reg_principal_info prin where prin.enrolReg.enrolNo=:ec"; for get value for enrolNO.

And the method is :

public EnrolRegPrinModel masterDetailsEC(String EC) throws Exception {
EnrolRegPrinModel ecDetails = new EnrolRegPrinModel();
Enrol_reg_principal_info info = new Enrol_reg_principal_info();

Session s = null;
try {
 s = sessionFactory.openSession();
String hql = " from Enrol_reg_principal_info prin where 
prin.enrolReg.enrolNo=:ec";
  Query q = s.createQuery(hql);
  q.setString("ec", EC);
info = (Enrol_reg_principal_info) q.uniqueResult();
} catch (Exception ex) {
 ex.printStackTrace();
} finally {
 s.close();

 }
 return ecDetails;
}

Please help. Thanks in advance

2 Answers

I think the issue is that you are trying to fetch results via uniqueResult method. Since it is a composite primary key there is a possibility that for the ec sent by you there are multiple records available in database and there is a thumb rule with uniqueResult that you should fetch one result only(even if no record is found then also you will face exception).

Try fetching the results as :

List<Enrol_reg_principal_info> info = (List<Enrol_reg_principal_info>) q.list();
Related