简体   繁体   中英

Hibernate Entity Class maps to two different Tables

I am trying to Map my @Entity objects to their respective classes where one is a parameter of the other.

To put it simply I have something like this:

@Entity
@Table(name="TableA")
public class ClassA {
    @Id
    private long id;

    private String paramA;

    private ClassB classB;

    // getters and setters here
}

ClassB looks like:

@Entity
@Table(name="TableB")
public class ClassB {
    @Id
    private long classAId;

    private String paramB;

    // getters and setters here
}

To save I am using the Interface - (I suspect this or the way I am using it is my problem?)

@Transactional
public interface ClassADao extends JpaRepository<ClassA, Integer> {

}

In my DB all parameters in ClassA map to a corresponding table except for ClassB which has parameters that all match to a different table for ClassB. I'm new to Hibernate and was hoping it would map the params of ClassB to the correct table. However it appears to be trying to map ClassB to a column in the table for ClassA and thus giving me this error:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'classB' in 'field list'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:941)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3870)

My question is, is there a way (preferably through Annotation) to tell Hibernate to make the params in ClassB map to it's own table? I have tried using @SecondaryTable but that didn't work.

Thanks in advance!

With help from the people who commented on this, I was able to come up with the following solution:

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;

@OneToOne(cascade = {CascadeType.ALL})
@PrimaryKeyJoinColumn
private ClassB classB;

public setClassB(ClassB classB) {
    this.classB = classB;
    this.classB.setClassA(this);
}

And edited ClassB like so:

@Entity
@Table(name="TableB")
public class ClassB {
    @MapsId
    @OneToOne
    @JoinColumn
    private ClassA classA

    private String paramB;

    // getters and setters here - including for ClassA

}

Now when I call the Spring injected ClassADao.save(classA) , ClassB also gets saved in the DB correctly for free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM