Hibernate how to use a constant as part of composite foreign reference

后端 未结 1 1375
小鲜肉
小鲜肉 2021-01-19 10:28

I have a master table A with a composite primary key, consisting of two columns. One of these columns is a constant (\"THE CONSTANT VALUE\"

1条回答
  •  被撕碎了的回忆
    2021-01-19 11:21

    I really wonder how it can be helpful to have a constant column value in a database, but anyway...

    What I would do is to only map the non-constant column as ID, and make the constant column a regular column, with a constant value:

    @Entity
    public class Strange {
        @Id
        private Long id;
    
        @Column
        private long constant = 345; // the constant that you want in your database
    
        @OneToMany(mappedBy = "strange")
        private Set details;
    
        ...
        // no setter for constant!
    }
    
    @Entity
    public class Detail {
       ...
       @ManyToOne
       @JoinColumn(name = "strange_id")
       private Strange strange;
    }
    

    If other entities reference this same Strange entity using its full composite key, then simply do the following:

    @Entity
    public class Strange {
        @Id
        @Column(name = "strange_id")
        private Long id;
    
        @Id
        private long constant = 345; // the constant that you want in your database
    
        @OneToMany(mappedBy = "strange")
        private Set details;
    
        ...
        // no setter for constant!
    }
    
    @Entity
    public class Detail {
       ...
       @ManyToOne
       @JoinColumn(name = "strange_id", referencedColumnName = "strange_id")
       private Strange strange;
    }
    

    You can reference other entities using something other than their PK. Another unique column is also OK. And since strange_id is unique, it fits the bill. The referencedColumnName attribute must be used to specify the referenced column name, in that case.

    0 讨论(0)
提交回复
热议问题