【问题标题】:Hibernate reference mapping休眠参考映射
【发布时间】:2023-04-02 20:29:01
【问题描述】:

我有一个婚姻状态表,其中包含“单身”、“已婚”等值。

我有一个表 Person,其中 marital_status_id 作为外键。

我如何映射这个?任何帮助将不胜感激,因为我是 Hibernate 的新手。或者我不需要这个,因为 Person 和 Marital Status 之间没有关系,而只是一个参考?

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    首先,婚姻状况不需要单独的表格(是吗?真的吗?)。可以用单个字符处理(非常高效)

    但是,在你的情况下,

    @Entity
    @Table(name="PERSON")
    Class Person(){
        @Id
        @Column(name = "ID", unique = true, nullable = false, precision = 15, scale = 0)
        private Long id;
    
        @ManyToOne(fetch=FetchType.LAZY)
        @JoinColumn(name="MARITAL_STATUS_ID")
        MaritalStatus maritalStatus;
    }
    

    @Entity
    @Table(name="MARITAL_STATUS")
    Class MaritalStatus(){
        @Id
        @Column(name = "ID", unique = true, nullable = false, precision = 15, scale = 0)
        private Long id;
    
        @OneToMany(mappedBy="maritalStatus")
        Set<Person> persons;
    }
    

    【讨论】:

    • 是的,我只是使用字符来消除不必要的表格。
    【解决方案2】:

    婚姻状况在 Java 中应表示为枚举,以排除不必要的连接,因为没有那么多选项,它们永远不会改变。
    检查@Enumerated(EnumType.STRING)注解:http://docs.oracle.com/javaee/6/api/javax/persistence/Enumerated.html

    【讨论】:

    • 它必须工作,因为基本上它所做的只是将值保存为字符串 - 从数据库的角度来看,java 的字符串变量和枚举之间没有区别 - 这仅涉及持久提供程序。请务必在持久性提供程序设置中选择 postresql 方言。
    【解决方案3】:

    你没有具体说明你是坚持建立一对一的关系还是不关心,以及你是否更喜欢使用 Enum 而不是 Class。

    这个链接提供了一些关于休眠中一对一映射的有用信息,如果你想在你的表之间建立这样的关系:one-to-one example

    不过不推荐使用 hibernate 的一对一映射,您可以像这样简单地使用一对多映射:

    @Entity
    @Table(name = "Person")
    public class Person {
    
        @Id
        @GeneratedValue
        int id; 
    
        @OneToMany(mappedBy = "Person", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        Private MaritalStatus;
    }
    
    @Entity
    @Table(name = "MaritalStatus")
    public class Person {
    
        @Id
        @GeneratedValue
        int id; 
    
        @ManyToOne
        Person person = new Person();
    }
    

    这种方法非常简单,但您可能更喜欢使用枚举而不是类,并使用枚举映射表。这种方法实施起来有点困难,这篇文章为你提供了你需要的所有东西:Mapping enum to a table

    【讨论】:

    • 我认为你的 @OneToMany@ManyToOne 注释颠倒了。
    【解决方案4】:

    我想在下面做

    个人实体:

    @Entity
    @Table(schema = "Person")
    public class Person {
        @Id
        private String id;
    
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "marital_status_id")
        private MaritalStatus  maritalStatus;
    
    }
    

    婚姻状况实体:

    @Entity
    @Table(schema = "MaritalStatus")
    public class MaritalStatus {
        @Id
        private String id;
    
        @Column(name = "status")
        private String status;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 2011-06-11
      相关资源
      最近更新 更多