如何往JoinTable中插入数据?

先上代码:
实体类:

@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……
}

仓库类:

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
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);

}

测试结果:hibernate自动生成了三张表:join_table_a,join_table_b,join_a2b,但是只有第一个测试方法可以在join_a2b表中留下记录,第二个测试方法并不能把两个实例一对一的关系记录在join_a2b中。

问题:请问是我的update方法写错了吗?我应该怎么写才能在进行update操作时更新join table呢?

阅读 1.5k
评论
    0 个回答
    撰写回答

    登录后参与交流、获取后续更新提醒