草庐IT

java - 创建完美的 JPA 实体

coder 2023-04-22 原文

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

7年前关闭。




Improve this question




我已经使用 JPA(实现 Hibernate)有一段时间了,每次我需要创建实体时,我都会发现自己在解决诸如 AccessType、不可变属性、equals/hashCode 等问题。
所以我决定尝试找出每个问题的一般最佳实践,并将其写下来供个人使用。
然而,我不介意任何人对此发表评论或告诉我我错在哪里。

实体类

  • 实现可序列化

    原因:规范说你必须这样做,但一些 JPA 提供者没有强制执行这一点。作为 JPA 提供程序的 Hibernate 不会强制执行此操作,但如果尚未实现 Serializable,它可能会因 ClassCastException 而在其胃深处的某个地方失败。

  • 构造函数
  • 使用实体的所有必需字段创建一个构造函数

    原因:构造函数应始终使创建的实例处于正常状态。
  • 除了这个构造函数:有一个包私有(private)默认构造函数

    原因:需要默认构造函数让Hibernate初始化实体; private 是允许的,但在没有字节码检测的情况下,运行时代理生成和高效数据检索需要包私有(private)(或公共(public))可见性。

  • 字段/属性
  • 在需要时使用一般的字段访问和属性访问

    原因:这可能是最有争议的问题,因为对于其中一个(属性(property)访问与字段访问)没有明确且令人信服的论据;然而,由于更清晰的代码、更好的封装以及不需要为不可变字段创 build 置器,字段访问似乎是普遍的最爱
  • 省略不可变字段的 setter (访问类型字段不需要)
  • 属性可能是私有(private)的
    原因:我曾经听说protected 对(Hibernate)性能更好,但我在网上能找到的只有:Hibernate 可以直接访问public、private 和protected 访问器方法,也可以直接访问public、private 和protected 字段。选择权取决于您,您可以根据自己的应用程序设计进行匹配。

  • 等于/哈希码
  • 如果此 id 仅在持久化实体时设置,则永远不要使用生成的 id
  • 根据偏好:使用不可变值形成唯一的业务 key 并使用它来测试相等性
  • 如果唯一的业务 key 不可用,请使用非暂时性 UUID 它是在实体初始化时创建的;见 this great article想要查询更多的信息。
  • 从不引用相关实体(ManyToOne);如果此实体(如父实体)需要成为业务 key 的一部分,则仅比较 ID。只要您使用 property access type,在代理上调用 getId() 就不会触发实体的加载。 .

  • 示例实体
    @Entity
    @Table(name = "ROOM")
    public class Room implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue
        @Column(name = "room_id")
        private Integer id;
    
        @Column(name = "number") 
        private String number; //immutable
    
        @Column(name = "capacity")
        private Integer capacity;
    
        @ManyToOne(fetch = FetchType.LAZY, optional = false)
        @JoinColumn(name = "building_id")
        private Building building; //immutable
    
        Room() {
            // default constructor
        }
    
        public Room(Building building, String number) {
            // constructor with required field
            notNull(building, "Method called with null parameter (application)");
            notNull(number, "Method called with null parameter (name)");
    
            this.building = building;
            this.number = number;
        }
    
        @Override
        public boolean equals(final Object otherObj) {
            if ((otherObj == null) || !(otherObj instanceof Room)) {
                return false;
            }
            // a room can be uniquely identified by it's number and the building it belongs to; normally I would use a UUID in any case but this is just to illustrate the usage of getId()
            final Room other = (Room) otherObj;
            return new EqualsBuilder().append(getNumber(), other.getNumber())
                    .append(getBuilding().getId(), other.getBuilding().getId())
                    .isEquals();
            //this assumes that Building.id is annotated with @Access(value = AccessType.PROPERTY) 
        }
    
        public Building getBuilding() {
            return building;
        }
    
    
        public Integer getId() {
            return id;
        }
    
        public String getNumber() {
            return number;
        }
    
        @Override
        public int hashCode() {
            return new HashCodeBuilder().append(getNumber()).append(getBuilding().getId()).toHashCode();
        }
    
        public void setCapacity(Integer capacity) {
            this.capacity = capacity;
        }
    
        //no setters for number, building nor id
    
    }
    

    非常欢迎添加到此列表中的其他建议...

    更新

    自阅读 this article我已经调整了我实现 eq/hC 的方式:
  • 如果有一个不可变的简单业务 key 可用:使用该
  • 在所有其他情况下:使用 uuid
  • 最佳答案

    JPA 2.0 Specification指出:

    • The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
    • The entity class must a be top-level class. An enum or interface must not be designated as an entity.
    • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
    • If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
    • Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.


    该规范不包含关于实体的 equals 和 hashCode 方法的实现的要求,据我所知只针对主键类和映射键。

    关于java - 创建完美的 JPA 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6033905/

    有关java - 创建完美的 JPA 实体的更多相关文章

    1. ruby - 如何在 Ruby 中顺序创建 PI - 2

      出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

    2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

      使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

    4. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

      我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

    5. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

      如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

    6. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

      关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

    7. java - 等价于 Java 中的 Ruby Hash - 2

      我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

    8. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

      我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

    9. java - 从 JRuby 调用 Java 类的问题 - 2

      我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

    10. ruby - 使用多个数组创建计数 - 2

      我正在尝试按0-9和a-z的顺序创建数字和字母列表。我有一组值value_array=['0','1','2','3','4','5','6','7','8','9','a','b','光盘','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','','u','v','w','x','y','z']和一个组合列表的数组,按顺序,这些数字可以产生x个字符,比方说三个list_array=[]和一个当前字母和数字组合的数组(在将它插入列表数组之前我会把它变成一个字符串,]current_combo['0','0','0']

    随机推荐