java - Hibernate @ManyToOne 映射 - 无需设置 @Id 属性即可自动加载

标签 java spring hibernate jpa orm

如何强制 Hibernate 加载我的主对象以及 ManyToOne 关系中的其他对象?此时需要设置除 @Id 属性之外的其他值。

你能在 github 上检查我的 Maven 项目仓库吗,HbnAddressDaoTest是一个 JUnit 测试类,我正在其中尝试这种行为

Address 是我想保留到数据库的实体类,但只有来自 Country 的国家/地区代码。 Country 表中的所有行都是常量,因此不应再次插入 Country 对象,只需写入 countryId 即可。 Hibernate 中是否有任何自动化机制来实现此目的,或者我是否必须在 Address 持久化之前在某些服务事务方法中手动加载 Country

最佳答案

不,这是不可能的,java无法知道new Country("BE")何时等于countryDao.getByCode("BE"),因为,没有平等的人,一个由 Hibernate 管理,另一个由您管理。

您没有将 new Country("BE") 提供给 Hibernate,因此它不可能相同,而且您调用了 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 构造函数设为私有(private)或 protected ,并且仅通过 CountryProvider 访问 Country

关于java - Hibernate @ManyToOne 映射 - 无需设置 @Id 属性即可自动加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535991/

相关文章:

spring - 配置文件中的管理器 Spring MVC @RequestMapping

java - sqlserver2010的maven依赖?

java - 提交请求时控件始终选择 GET 方法而不是 POST

java - 无法使用 hibernate PostgreSQL 存储 java.time.ZonedDateTime

java - 如何更改j_security_check使用的原始请求页面?

java - Math.round() 无法正常工作

java - 引用索引数组

java - java中的 boolean 赋值

java - 无法初始化代理 - 没有 session ?

java - hibernate MySQL