Code first:
entity class:
@Entity
@Table(name = "joinTable_a")
public class JoinTableA {
@Id @GeneratedValue private long id;
private String name;
@OneToOne
@JoinTable(name = "join_a2b", joinColumns = @JoinColumn(name = "aid"),
inverseJoinColumns = @JoinColumn(name = "bid"))
private JoinTableB joinTableB;
//getter and setter
}
@Entity
@Table(name = "joinTable_b")
public class JoinTableB {
@Id @GeneratedValue private long id;
private String name;
@OneToOne(mappedBy = "joinTableB")
private JoinTableA joinTableA ;
//getter and setter
}
Warehouse class:
public interface JoinTableARepository extends JpaRepository<JoinTableA, Long> {
@Modifying
@Transactional
@Query("update JoinTableA j set j.joinTableB =?2 where j.id=?1")
public void update(long id, JoinTableB joinTableB);
}
public interface JointableBRepository extends JpaRepository<JoinTableB, Long> {
@Modifying
@Transactional
@Query("update JoinTableB j set j.joinTableA =?2 where j.id =?1 ")
public void update(long id, JoinTableA joinTableA);
}
Test Code:
@Test
public void test_add(){
JoinTableA joinTableA = new JoinTableA("joina");
JoinTableB joinTableB = new JoinTableB("joinb");
long id1=repositorya.saveAndFlush(joinTableA).getId();
long id2=repositoryb.saveAndFlush(joinTableB).getId();
repositoryb.update(id2, joinTableA);
repositorya.update(id1, joinTableB);
}
@Test
public void test_add1(){
JoinTableA joinTableA = new JoinTableA("joina");
JoinTableB joinTableB = new JoinTableB("joinb");
joinTableA = repositorya.saveAndFlush(joinTableA);
joinTableB = repositoryb.saveAndFlush(joinTableB);
joinTableA.setJoinTableB(joinTableB);
joinTableB.setJoinTableA(joinTableA);
repositorya.saveAndFlush(joinTableA);
repositoryb.saveAndFlush(joinTableB);
}
Test results: hibernate automatically generates three tables: join_table_a,join_table_b,join_a2b, but only the first test method can record in the join_a2b table, and the second test method cannot record the one-to-one relationship between the two instances in join_a2b.
question: is my update method written wrong? How should I write to update join table during update operations?