簡體   English   中英

與EJB保持多對多關系

[英]persist many-to-many relationship with EJB

我正在使用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方法不為null。 你能告訴我如何解決。 謝謝

如果要在容器包含新對象時將其持久化,則需要將關系上的@CascadeType設置為包括PERSIST

這在幾個實體中對我有用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM