如何在SpringBoot中使用Hibernate @NaturalId?

解道jdon 2021-05-04 17:27:09
SpringBoot 使用 Hibernate 中使 何在


这是一个Spring Boot应用程序案例,展示如何使用Hibernate映射自然业务键  @NaturalId。

关键点:

1.在实体(例如,Product)中,标记应作为自然ID 的属性(业务键)  @NaturalId; 通常,实体中只有一个这样的属性,但是这里也支持多个属性。

@Entity
public class Product implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @NaturalId(mutable = false)
    @Column(nullable = false, updatable = false, unique = true, length = 50)
    private String code;
     // @NaturalId(mutable = false)
    // @Column(nullable = false, updatable = false, unique = true)
    // private Long sku;

对于不可变的id,将列标记为@NaturalId(mutable = false)和@Column(nullable = false, updatable = false, unique = true, ...)

对于可变id,将列标记为@NaturalId(mutable = true)和 @Column(nullable = false, updatable = true, unique = true, ...)

2. 使用自然id覆盖equals()和hashCode()

  @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Product)) {
            return false;
        }
        Product naturalIdProduct = (Product) o;
        return Objects.equals(getCode(), naturalIdProduct.getCode());
        // including sku 
        // return Objects.equals(getCode(), naturalIdProduct.getCode())
            // && Objects.equals(getSku(), naturalIdProduct.getSku());
    }
    @Override
    public int hashCode() {
        return Objects.hash(getCode());
        // including sku
        // return Objects.hash(getCode(), getSku());
    }
    @Override
    public String toString() {
        return "Product{" + "id=" + id + ", name=" + name + ", code=" + code + '}';
        // including sku
        // return "Product{" + "id=" + id + ", name=" + name + ", code=" + code + ", sku=" + sku + '}';
    }

3. 定义一个@NoRepositoryBean接口(例如NaturalRepository)来定义两个名为findBySimpleNaturalId()and的方法findByNaturalId() 

@NoRepositoryBean
public interface NaturalRepository<T, NID extends Serializable> {
    // use this method when your entity has a single field annotated with @NaturalId
    Optional<T> findBySimpleNaturalId(NID naturalId);
     
    // use this method when your entity has more than one field annotated with @NaturalId
    Optional<T> findByNaturalId(Map<String, Object> naturalIds);        
}

4. 提供此接口的实现(例如,一个NaturalRepositoryImpl实现  )依赖于Hibernate的Session实现 bySimpleNaturalId(),和  byNaturalId()方法

@Repository
@Transactional(readOnly = true)
public abstract class NaturalRepositoryImpl<T, NID extends Serializable>
        implements NaturalRepository<T, NID> {
    @PersistenceContext
    private EntityManager entityManager;
    private final Class<T> entityClass;
    public NaturalRepositoryImpl(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
    @Override
    public Optional<T> findBySimpleNaturalId(NID naturalId) {
        Optional<T> entity = entityManager.unwrap(Session.class)
                .bySimpleNaturalId(entityClass)
                .loadOptional(naturalId);
        return entity;
    }
    @Override
    public Optional<T> findByNaturalId(Map<String, Object> naturalIds) {
        NaturalIdLoadAccess<T> loadAccess
                = entityManager.unwrap(Session.class).byNaturalId(entityClass);
        naturalIds.forEach(loadAccess::using);
        return loadAccess.loadOptional();
    }
}

对于实体,编写扩展的存储库类(例如,用于Product实体写入  ProductNaturalRepository)NaturalRepositoryImpl并使用它来设置实体类类型和自然id类型(当实体使用多个自然ID时,类型不再相关,只需将其设置为Serializable)

45 在您的服务中注入此类并调用findBySimpleNaturalId()或 findByNaturalId()

源代码可在此处获得

版权声明
本文为[解道jdon]所创,转载请带上原文链接,感谢
https://www.jdon.com/51829

  1. Compare node.js with spring boot- Ryan Gleason
  2. Obvious pitfalls of spring Webflux- Ł ukaszKy ć
  3. Spring founder uncle rod's real thoughts on yaml
  4. 码农飞升记-02-OracleJDK是什么?OracleJDK的版本怎么选择?
  5. What is manong feisheng-02-oracle JDK? How to choose the version of Oracle JDK?
  6. Spring tide surging Xinanjiang
  7. Linux内核软中断
  8. Linux kernel soft interrupt
  9. Linux内核软中断
  10. Linux kernel soft interrupt
  11. Java multithreading Foundation
  12. The construction of Maven private library nexus
  13. I / O stream in Java
  14. JDK 16:Java 16的新功能 - InfoWorld
  15. 在Java中本地进行线程间数据传输的三种方式和源码展示
  16. jdon导致cpu 99%最后tomcat死掉---banq给予回复
  17. 用领域事件模拟AOP注入
  18. JDK 16: new function of Java 16 - InfoWorld
  19. Cartoon: from JVM lock to redis distributed lock
  20. Spring 3.1 终于加入了Cache支持
  21. Prototype与JQuery对比
  22. Three ways of data transmission between threads in Java and source code display
  23. Jdon causes 99% of CPU and Tomcat dies -- banq replies
  24. docker 原理之 user namespace(下)
  25. Simulating AOP injection with domain events
  26. Spring 3.1 finally adds cache support
  27. Comparison between prototype and jquery
  28. User namespace of docker principle (2)
  29. The way to learn java IO stream and XML
  30. Why does a seemingly correct code cause the Dubbo thread pool to be full
  31. 0 基础 Java 自学之路(2021年最新版)
  32. 0 basic Java self study road (latest version in 2021)
  33. c#—基础拾遗(1) 面向对象
  34. C - basic information (1) object oriented
  35. 技术分享|SQL和 NoSQL数据库之间的差异:MySQL(VS)MongoDB
  36. Technology sharing differences between SQL and NoSQL databases: MySQL (VS) mongodb
  37. PHP教程/面向对象-3~构造函数和析构函数
  38. Spring Cloud的Feign客户端入门
  39. 优化Spring Boot应用的Docker打包速度
  40. PHP tutorial / object oriented - 3 ~ constructor and destructor
  41. Introduction to feign client of spring cloud
  42. Optimizing docker packaging speed of spring boot application
  43. 尚硅谷宋红康Java基础教程2019版
  44. 尚硅谷宋红康Java基础教程2019版
  45. Song Hongkang Java foundation course 2019
  46. Song Hongkang Java foundation course 2019
  47. Redis 6 的多线程
  48. Multithreading of redis 6
  49. SpringCloud-微服务架构编码构建
  50. SpringCloud-微服务架构编码构建
  51. Linux作业控制
  52. Coding construction of springcloud microservice architecture
  53. Java中几个常用并发队列比较 | Baeldung
  54. 为什么Java后端在创业企业中并不流行? -reddit
  55. Coding construction of springcloud microservice architecture
  56. Linux job control
  57. Comparison of several common concurrent queues in Java
  58. Why is java backend not popular in start-ups- reddit
  59. docker 资源限制之 cgroup
  60. 大数据环境: hadoop和jdk部署