2014-08-27 66 views
0

如何強制Hibernate加載我的主對象與其他對象ManyToOne關係?這是設置其他一些值的時刻,除@Id屬性外。Hibernate @ManyToOne映射 - 無需@Id屬性設置的自動加載

你可以檢查我的在github Maven項目回購,HbnAddressDaoTest是一個JUnit測試類這裏我想這種行爲

Address是實體類,我想堅持到數據庫中,但只有從國家代碼CountryCountry表中的所有行都是常量,因此不應再插入Country對象,只需要寫入countryId。在Hibernate中是否有任何自動化機制?或者我必須在Address持續之前在某些服務事務方法中手動加載Country

回答

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構造函數都是私有的或受保護的,並且只能通過CountryProvider訪問Country

+0

如果hibernate在執行get()方法時不能看到構造函數,hibernate會如何加入到該地址中? – shx 2014-08-28 19:08:31

+1

通過反思,構造函數是必需的,但可見性可以是私有的。 – 2014-08-28 19:40:48

+0

我有一個想法,將Dozer從JAXB映射到我的域類。在JAXB模型中,我只有那個國家代碼。我必須在堅持之前把它放在某個地方。因爲創建「新的國家」(「BE」)在我的測試中。在映射我的國家對象中的所有值之後,都是'null',除了'code' – shx 2014-08-28 20:08:12