@Entity
@Table(name = "applicant")
public class Applicant implements Serializable {
private static final long serialVersionUID = -8634638904962909584L;
// Primary id required by Hibernate
@Id
@GeneratedValue(strategy=IDENTITY)
@Column(name = "applicant_id", nullable=false, unique=true)
private Long applicantId; // Unique id for each applicant
@OneToOne(cascade = CascadeType.ALL)
@Fetch(value = FetchMode.SELECT)
@JoinColumn(name = "applicant_id", referencedColumnName= "applicant_id")
private DS1350 ds1350;
public Applicant () {
}
}
@Entity
@Table(name = "ds_1350")
public class DS1350 implements Serializable {
private static final long serialVersionUID = -7370747595057569296L;
// Primary id required by Hibernate
@Id
@GeneratedValue(strategy=IDENTITY)
@Column(name = "ds_1350_id", nullable=false, unique=true)
private Long ds1350Id;
@Column(name = "applicant_id", unique=true, nullable=false)
// @GeneratedValue(generator="gen")
// @GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name = "property", value = "applicant"))
private Long applicantId; // Unique id for each applicant
@Column(name = "ds1350_no", length = 50)
private String ds1350Number;
}
public class ApplicantDaoTest {
@Autowired
private ApplicantDao applicantDao;
private Applicant applicant;
private DS1350 ds1350 = new DS1350();
@BeforeClass
public static void beforeClass() {
}
@AfterClass
public static void afterClass() {
}
@Before
public void setup() {
this.initApplicant();
}
@After
public void teardown() {
}
private void initApplicant() {
applicant = new Applicant();
applicant.setFirstName("John");
Calendar calendar = Calendar.getInstance();
applicant.setDob(calendar);
applicant.setSsn("123456789");
applicant.setCreatedBy("JUNIT");
applicant.setCreatedDate(Calendar.getInstance());
applicant.setModifiedBy("JUnit");
applicant.setModifiedDate(Calendar.getInstance());
this.initDS1350();
}
private void initDS1350 () {
ds1350.setDs1350Number("ds1350Number");
ds1350.setCreatedBy("JUNIT");
ds1350.setCreatedDate(Calendar.getInstance());
applicant.setDs1350(ds1350);
}
@Test
public void testSaveApplicant() {
Long applicantId = applicantDao.saveApplicant(applicant);
applicant = applicantDao.getApplicantByPrimaryKey(applicantId);
assertTrue("ds1350Number".equals(applicant.getDs1350().getDs1350Number()));
}
}
这是 ds1350 和申请类别的代码。我使用休眠会话 save() 来保存申请人对象中包含 ds1350 的申请人。我有 OneToMany 非常好,但这个 OneToOne 不起作用。由于外键(ds1350 中的 applicant_id)被保存为 null 并且 applicationDao.getApplicantByPrimaryKey(applicantId) 无法获取 ds1350 对象,因此申请者.getDs1350() 抛出 NullPointerException。