我怎么能强制Hibernate来加载我的主要对象从多对一的关系其他对象? 这就是一些其他的值设置的那一刻,比其他@Id
属性。
你可以检查我的在github Maven项目回购, HbnAddressDaoTest是一个JUnit测试类这里我想这种行为
Address
是实体类,我想坚持到数据库,但只能从有国家代码Country
。 在所有行Country
表是常数,所以Country
的对象不应该再次插入,只countryId
需要被写入。 是否有任何的Hibernate自动化机制这还是我不得不手动加载Country
在之前的一些服务交易方法Address
持久性?
不,这不是更多钞票,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
建设者私人或受保护的,只有进入Country
由CountryProvider
。