不,不可能,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
构造函数都是私有的或受保护的,并且只能通过CountryProvider
访问Country
。
如果hibernate在执行get()方法时不能看到构造函数,hibernate会如何加入到该地址中? – shx 2014-08-28 19:08:31
通过反思,构造函数是必需的,但可见性可以是私有的。 – 2014-08-28 19:40:48
我有一个想法,将Dozer从JAXB映射到我的域类。在JAXB模型中,我只有那个国家代码。我必须在坚持之前把它放在某个地方。因为创建“新的国家”(“BE”)在我的测试中。在映射我的国家对象中的所有值之后,都是'null',除了'code' – shx 2014-08-28 20:08:12