2014-08-27 62 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