Reputation: 3192
Thanks to Predrag Maric I managed to find a bug which was that referencedColumnName was not referring to the right field. then I had to make the Table2 class implement the Serializable Interface and this made my test pass
Thanks for your help
How can I map Table3 in Hibernate?
This is my attempt:
@Entity
@Table(name="Table3")
public class Table3 implements Serializable
{
@Id
@GeneratedValue
private long id;
@NotNull
@Column(name="field1")
private String field1;
@NotNull
@Column(name="field2")
private String field2;
@ManyToOne
@JoinColumn(name="Table2_id")
private Table2 Table2_id ;
@ManyToOne
@JoinColumn(name="Table2_Table1_username")
private Table2 Table2_Table1_username;
The error is in my JUnit test:
Cannot add or update a child row: a foreign key constraint fails (
database.
Table3, CONSTRAINT
fk_Table3_Table2FOREIGN KEY (
Table2_id,
Table2_Table1_username) REFERENCES
Table2(
id,
Table1_username) ON DELETE NO ACTION ON UPDATE NO ACTION)
Constructor:
Table3(String field1, String field2, Table2 table)
{
this.field1 = field1;
this.field2 = field2;
this.Table2_id = table;
this.Table2_Table1_username = table;
}
JUnit Test
@Before
public void init()
{
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("DELETE FROM Table3");
jdbc.execute("DELETE FROM Table2");
jdbc.execute("DELETE FROM Table1");
}
@Test
public void testCreateMedia()
{
table1DAO.createTable(table1Object);
table2DAO.createTable(table2Object);
table3DAO.createTable(table3Object); //fails here
}
Noted: I am not using java naming convention for variables
Upvotes: 1
Views: 1921
Reputation: 24403
I think you misunderstood name
and referencedColumnName
in @JoinColumn
.
name
is the name of the column in source (Table3
) table which is a foreign key to target (Table2
) table.
referencedColumnName
is the name of the column in target table which is a primari key (Table2.id
). This attribute can be omitted in most cases.
In your case, it should look like this
@ManyToOne
@JoinColumn(name="Table2_id")
private Table2 Table2_id ;
@ManyToOne
@JoinColumn(name="Table2_Table1_username")
private Table2 Table2_Table1_username;
Upvotes: 3