Is it possible to map a field in an Entity without defining any association?

后端 未结 2 1431
Happy的楠姐
Happy的楠姐 2021-02-09 03:38

I\'ve got the following schema in DB (simplified)

MainTable(
    ID primary key
    SOMEFIELD
    CODE_FK1 -- references OtherTable1 CODE (without declared forei         


        
相关标签:
2条回答
  • 2021-02-09 04:18

    You can use the @SecondaryTable annotation. See this example:

    https://github.com/hibernate/hibernate-orm/blob/823a5c1ede1869fd97471e3b8ebe7ec4ac8068e4/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Dog.java#L20-L24

    0 讨论(0)
  • 2021-02-09 04:20

    Another possibility would be using the @Formula annotation to fetch the value from the other table. This will automatically generate a subselect whenever you load your Entity.

    I think you'll need something like this:

        @Entity
    public class MainEntity{
        @Id
        private Integer ID;
    
        @Column(name="SOMEFIELD")
        private String SomeField;
    
        @Formula("(SELECT ot1.LABEL FROM OtherTable1 ot1 WHERE ot1.CODE = CODE_FK_1)")
        private String Label1;
    
    }
    

    There is little information about this in the [Hibernate docs][1], so you may need some trial and error to get it right (but you should be able to work it out with hibernate.show_sql=true.

    There are 2 possible downsides to this approach:

    1. This is hibernate-specific code
    2. This is plain SQL, and may thus be database-specific

    HTH

    [1]: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-property hibernate docs

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