不,不可能,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