【问题标题】:JPA. Many to Many creates duplicated rowsJPA。多对多创建重复行
【发布时间】:2015-02-05 21:12:02
【问题描述】:

请帮助我了解我错在哪里。 我有三张桌子:

餐桌愿望

CREATE TABLE WISHES(
  wish_id bigint default nextval('wish_id_inc'::regclass),
  target text not null,
  PRIMARY KEY(wish_id)
)

表格标签

CREATE TABLE TAGS(
  tag character varying(255) not null,
  PRIMARY KEY(tag)
)

表 Wish_tags

CREATE TABLE wish_tags(
  wish_tags bigint default nextval('wish_tags_id_inc'::regclass),
  wish_id bigint references wishes(wish_id),
  tag_id character varying(255) references tags(tag),
  PRIMARY KEY(wish_tags)
)

我为这些表创建了两个类:

@Entity
@Table(name="wishes")
public class Wish  implements Serializable{
...
      @ManyToMany
      @JoinTable(
          name="wish_tags",
          joinColumns={@JoinColumn(name="wish_id", referencedColumnName="wish_id")},
          inverseJoinColumns={@JoinColumn(name="tag_id", referencedColumnName="tag")})
    private List<Tag> tags;
...
}
    @Entity
    @Table(name="tags")
    public class Tag implements Serializable{
        ...
        @ManyToMany(mappedBy="tags")
        private List<Wish> whishes;
        ...
    }

当我尝试使用标签创建愿望时,我会复制到 wish_tags 表中。

@Transactional
public Wish createWish(List<String> tags){
//em is EntityManager
        ArrayList<Tag> ObTags = new ArraList<Tag>();
        for(String tagId: tags){
            Tag tag = new Tag(tagId);
            ObTags.add(em.merge(tag));
        }
        Wish wish = new Wish(args1,..., ObTags);
        em.persist(wish);
    }

我做错了什么?为什么要创建重复项?请帮帮我。

【问题讨论】:

  • 你可以在 ManyTOMany 声明中使用@Column(insertable=false, updatable =false) 属性。

标签: java sql hibernate jpa


【解决方案1】:

两个标签保存在 DB 中,因为一个保存在 EntityManager.merge(tag) 上,另一个保存在级联 EntityManager.persist(wish)ObTags 集合中。

【讨论】:

  • 感谢您的回答,但这是我的代码错误,我将相同的标签两次放入 ObTags。 ObTags 没有任何级联到 Wish。我可以如果我没有指定任何级联,那么休眠不应该保存 ObTags。是真的吗?
【解决方案2】:

对不起,这是我的代码错误。我将相同的标签两次放入wish。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2021-07-31
    • 2014-04-14
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多