【问题标题】:persist many-to-many relationship with EJB与 EJB 保持多对多关系
【发布时间】:2013-08-08 06:04:20
【问题描述】:

我正在使用 JPA(休眠)、EJB 和 CDI bean (JSF)。我有两个表:技术(实体是 Technology.class)和组件(实体是 Component.class)具有多对多关系。 实体代码:

public class Technology implements Serializable{
...
@Lob
@Column(nullable=false)
private String title;
...
@ManyToMany(mappedBy="technologies")
private List<Component> components;
..
}

public class Component implements Serializable {
...
@ManyToMany
    @JoinTable(
        name="technology_has_component"
        , joinColumns={
            @JoinColumn(name="component_title", nullable=false)
            }
        , inverseJoinColumns={
            @JoinColumn(name="technology_tId", nullable=false)
            }
        )
    private List<Technology> technologies;
...
}

EJB 中的代码:

@Stateless
@LocalBean
public void addTech(Technology tech) throws Exception {     
    em.persist(tech);
}

我的 JSF 页面使用带有属性和方法的 CDI bean:

    @Named(value = "adminActionTech")
    @SessionScoped
    public class AdminActionTech implements Serializable{
    ...

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String addTech() {
        Technology tech = new Technology();
        tech.setTitle(title);
            ...

        tech.setComponents(getListAvaiComps());
        try {
             techService.addTech(tech); 
        } catch (Exception e) {
             e.printStackTrace();
        }
    }
    private List<Component> getListAvaiComps() {
          List<Component> listNewComponent = new ArrayList<Component>();
          Component findComp = compService.findComp(component.getTitle()); // findComp() is a method in a EJB
          listNewComponent.add(findComp);
          return listNewComponent;
    }

当我添加带有标题的新技术时,....,列出组件。一切都很好,除了没有添加列表组件。我检查了技术表,创建了一条新记录,但 technology_has_component 表没有添加更多记录。 我调试并确定 getListAvailComps 方法不为空。 你能告诉我如何解决。谢谢

【问题讨论】:

    标签: java jpa ejb


    【解决方案1】:

    如果您希望新对象在其容器存在时保持不变,则需要将关系上的 @CascadeType 设置为包括 PERSIST 在内的内容。

    【讨论】:

    • 很抱歉,没有任何变化
    【解决方案2】:

    这在几个实体中对我有用

    在 Technology.java 中

    @ManyToMany
    @JoinTable(name = "technologiescomponents")
    private Set<Component> components;
    

    在 Component.java 中

    @ManyToMany(mappedBy = "components")
    private Set<Technology> technologys;
    

    对于数据库

    CREATE TABLE technologiescomponents
    (
      component_id bigint NOT NULL,
      product_id bigint NOT NULL
    );
    

    【讨论】:

    • @JoinTable 应该在关系的拥有方
    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2011-03-07
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多