如果@EmbeddedId的Any字段值为null,会出现什么问题?

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

我正在获取有关 Hibernate @EmbeddedId 的问题。我的@EmbeddedId 的代码是:

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

我的实体 class 是:

@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")
}

问题是:当 enrolNo 和 regNo 都有值时,我从 'Enrol_reg_principal_info' class 获取数据。但是当 enrolNo 或 regNo 有值时得到 NUllPointerException。

hql 是: String hql = " from Enrol_reg_principal_info prin where prin.enrolReg.regNo=:id"; 获取 regNo.

的值

String hql = " from Enrol_reg_principal_info prin where prin.enrolReg.enrolNo=:ec"; 获取 enrolNO 的值。

方法是:

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

请帮忙。提前致谢

当您说 EmbeddedId 时,它表示复合主键,它需要一个非空且唯一的值。 JPA 期望这些列是非空且唯一的。根据那个选择你的列。

休眠参考: http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite-aggregated

此外,我不确定您是否已经有了 getter 和 setter。嵌入式 ID class 需要正确设置 equals()hashcode() 方法。

我认为问题在于您正试图通过 uniqueResult 方法获取结果。因为它是一个复合主键,所以对于你发送的 ec 有可能在数据库中有多个可用记录并且有一个经验法则 uniqueResult 你应该只获取一个结果(即使没有记录是发现你也会面临异常)。

尝试获取结果为:

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