Hibernate: @SecondaryTable doesn't work

I know the problems @SecondaryTable

have been posted many times, so if there is one and the same (I haven't found it yet) please give me a link or advice.

I have two tables in my database ( firstTable

and secondTable

), two classes POJO Hibernate ( FirstTablePojo

and SecondTablePojo

).

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

      

I want to show fields from both of these tables in jsp from one list object, I decided to use @SecondaryTable

. These two tables are related by a field featureId

(which is the primary key for secondTable

), I want the featureName

from to secondTable

be displayed along with the from fields firstTable

. Before is FirstTablePojo

preceded by this annotation:

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

      

I added this property to FirstTablePojo

(with getters and setters):

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

      

When with using <c:forEach items="${features}" var="feature">

I get each ${feature.foo}

( foo

is the property that was in FirstTablePojo

before I used @SecondaryTable

) and ${feature.featureName}

, I see each foo

, but none of featureNames

it appears. It would be great if someone could tell me what I am missing here and why function names from another table are not showing up in the object list FirstTablePojo

.

+3


source to share


2 answers


An annotation point @SecondaryTable

should map the fields of one feature to multiple tables, just as if these tables were merged into one.

@ManyToOne is used to map a one-to-two association between two objects. But you have it. It makes no sense in this context. And @JoinColumn is used to indicate that the field is mapped to a column that is 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, for example, in the Hibernate documentation .

+7


source


It makes sense to use it @JoinColumn

if you want to put a foreign key field that represents the identifier of another entity in a secondary table. In this case, the correct way would be:



 @OneToOne
 @JoinColumn(name="another_entity_id", table="secondTable")
 AnotherEntity anotherEntity;

      

0


source







All Articles