Hibernate : @SecondaryTable doesn't work

2020-07-13 11:50发布

I know, @SecondaryTable issues were published numerous times, so, if there is the same one (I haven't found it yet), please, give me the link or an advice.

I have two tables in my database (firstTable and secondTable), two POJO Hibernate classes (FirstTablePojo and SecondTablePojo).

+----------+             +-----------+
|firstTable|             |secondTable|
|----------+             |-----------+
|featureId |------------>|featureId  |(secondTable's primary key)
|foo       |             |featureName|
|bar       |             +-----------+
+----------+

I want to show fields from both these tables in the jsp from the single list object, I decided to use @SecondaryTable. These two tables are connected by the featureId field (which is a primary key for the secondTable), I want the featureName from the secondTable to be shown along with fields from the firstTable. The FirstTablePojo is preceded by this annotation:

@SecondaryTable(name="secondTable", 
    pkJoinColumns=@PrimaryKeyJoinColumn(name="featureId", 
                                        referencedColumnName = "featureId"))

I added this property to the FirstTablePojo (with getters and setters):

 @ManyToOne
 @JoinColumn(name="featureId", table="secondTable")
 String featureName;

When with a help of <c:forEach items="${features}" var="feature">, I get each ${feature.foo} (foo is a property that was in the FirstTablePojo before I used @SecondaryTable) and ${feature.featureName}, I see each foo, but none of the featureNames appear. It'd be great if someone could tell me what do I miss here and why feature's names from the other table do not appear in the list of FirstTablePojo objects.

2条回答
forever°为你锁心
2楼-- · 2020-07-13 11:56

The point of the @SecondaryTable annotation is to map the fields of a single entity to several tables, exactly as if those tables were merged into a single one.

@ManyToOne is used to map a many-to-one association betwen two entities. But you just have one. It makes no sense in this context. And @JoinColumn is used to indicate that a field is mapped to a column that constitutes a ... join column, i.e. a foreign key to another table. So it doesn't make sense either.

Just use the following mapping:

@Column(name="featureName", table="secondTable")
String featureName;

This is well explained, with an example, in the Hibernate documentation.

查看更多
欢心
3楼-- · 2020-07-13 12:09

It makes sense to use @JoinColumn if you want to put a foreign key field, which represents an ID of another entity, into a secondary table. In this case, the correct way would be:

 @OneToOne
 @JoinColumn(name="another_entity_id", table="secondTable")
 AnotherEntity anotherEntity;
查看更多
登录 后发表回答