-->

休眠@ManyToOne制图 - 自动加载无需@Id属性集(Hibernate @ManyToOne

2019-11-03 07:16发布

我怎么能强制Hibernate来加载我的主要对象从多对一的关系其他对象? 这就是一些其他的值设置的那一刻,比其他@Id属性。

你可以检查我的在github Maven项目回购, HbnAddressDaoTest是一个JUnit测试类这里我想这种行为

Address是实体类,我想坚持到数据库,但只能从有国家代码Country 。 在所有行Country表是常数,所以Country的对象不应该再次插入,只countryId需要被写入。 是否有任何的Hibernate自动化机制这还是我不得不手动加载Country在之前的一些服务交易方法Address持久性?

Answer 1:

不,这不是更多钞票,Java可以不知道什么时候new Country("BE")等于countryDao.getByCode("BE")因为,没有平等的,一个是由Hibernate来管理的,另一种是由您管理。

你不给new Country("BE")冬眠,所以它不可能是相同的,也去你调用new Countru("BE")code为空,以及代码countryDao.getByCode("BE")不为空(它是由你的SQL脚本创建,现在是管理由Hibernate)。

你有两个选择:

  • 改变你的测试:

     Country country = countryDao.getByCode("BE"); Address address = new Address(); address.setCountry(country); addressDao.create(address); assertEquals(country.getCountryId(), addressDao.get(address.getAddressId()).getCountry().getCountryId()); 

    为了测试地址是否正确坚持着,或:

  • 创建CountryProvider是这样的:

     public class CountryProvider { @Autowired HbnCountryDao dao; Map<String, Country> map = new HashMap<String, Country>(); public Country getByCode(String code) { if (map.contains(code)) return map.get(code); Country toRet = dao.getByCode(code); map.put(code, toRet); return toRet; } } 

    让所有的Country建设者私人或受保护的,只有进入CountryCountryProvider



文章来源: Hibernate @ManyToOne mapping - automatic loading without @Id property set