How to configure multiple one to many relationship to the same entity?
Consider two classes Boy and Toy. They look as shown below
class Boy {
@OneToMany(mappedBy='ownedBy',fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private List<Toy> bikes;
...
@OneToMany(mappedBy='ownedBy',fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private List<Toy> cars;
...
class Toy {
@ManyToOne
private Boy ownedBy;
...
I know that this config is wrong. But I dont know what needs to be configured here.
What configuration should be made to the @OneToMany
and @ManyToOne
annotations, both sides?
I got the following exception message before I added the 'mappedBy' to the annotations
java.sql.SQLException: Field 'cars_Id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2444)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1997)
But there was a join table like 'boy_toy' created when there was no 'mappedBy' added to the annotation. After adding it I don't see the table created in the database.
- Update
Also boy_toy table had three columns namely boy_id, cars_id and bikes_id. But ideally it should be like boy_id a not null and others nullable columns. But all the columns generated were not-nullable. I tried to remove the 'mappedBy' from the annotation and manually edit the table structure to make cars_id and bikes_id to nullable. It worked like a wonder.
So now, the only remaining question I have is
How can we dictate hibernate to configure a join table with nullable and not-nullable columns?