【发布时间】:2014-02-19 15:22:24
【问题描述】:
我正在使用 Hibernate 4 和 Spring Data JPA,我与 FetchType.EAGER 有 ManyToOne 关系,Contact 有很多地址,我的问题是当我运行测试时,我无法在 Contact 实体中获取填充的集合,但如果我检索我可以访问联系人实体的地址实体。
这是联系实体代码:
@Entity(name = "CONTACT")
public class ContactJPA {
@OneToMany(mappedBy = "contact", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<AddressJPA> addresses;
//getters an setters
}
这是地址实体代码:
@Entity(name = "ADDRESS")
public class AddressJPA {
@ManyToOne(optional=false)
@JoinColumn(name="CONTACT_ID", referencedColumnName = "CONTACT_ID", nullable = false)
private ContactJPA contact;
//getters an setters
}
为了检索和保存实体,我使用 Spring 框架中的 CrudRepository。
这是我的junit:
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAConfigurationTest.class })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class ContactRepositoryIntegrationTest {
@Autowired
ContactRepository contactRepository;
@Autowired
AddressRepository addressRepository;
AddressJPA addressJPA;
Integer key = 1;
@Before
public void setUp(){
addressJPA = new AddressJPA();
addressJPA = new AddressJPA();
addressJPA.setAddressId(new Integer(1));
addressJPA.setCountry("Argentina");
addressJPA.setCity("Cordoba");
addressJPA.setStreet("San Juan");
}
@Test
public void thatRetrieveContactShouldPopulateAddress(){
ContactJPA contact = new ContactJPA();
contact.setContactId(key);
contact.setEmail("test@email.com");
contact = contactRepository.save(contact);
addressJPA.setContactJPA(contact);
addressRepository.save(addressJPA);
AddressJPA retrievedAddress = addressRepository.findByAddressId(1);
System.out.println("Address " + retrievedAddress);
ContactJPA retrievedContact = contactRepository.findByContactId(key);
System.out.println(retrievedContact.toString());
assertNotNull(retrievedContact);
assertEquals(key, retrievedContact.getContactId());
assertEquals(1, contact.getAddresses().size());//this throws null pointer exception
Iterator<AddressJPA> it = contact.getAddresses().iterator();
assertEquals(addressJPA, it.next());
}
}
有什么建议吗? 提前致谢
【问题讨论】:
-
我要问的第一个问题是在这种情况下你真的想要双向关系吗? JPA 不需要它们,它们可能会变得过于复杂。
标签: hibernate jpa junit4 spring-data