如何往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呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论