巴巴运动网 17 无限级产品归类的双向一对多JPA映射

巴巴运动网 17 无限级产品分类的双向一对多JPA映射


首先:结合 巴巴运动网 16,

结合 巴巴运动网 16节 增添

在 ProductType.java类中,增添如下属性:


    /** 子类别 **/
    private Set<ProductType> childtypes = new HashSet<ProductType>();

    /** 所属 父类 **/
    private ProductType parent;

    // optional=true 可以选择吗 ? 这里指的是:可以没有父类。
    @ManyToOne(cascade = CascadeType.REFRESH, optional = true)
    @JoinColumn(name = "parentid")  // 此为 外键。
    public ProductType getParent() {
        return parent;
    }

    public void setParent(ProductType parent) {
        this.parent = parent;
    }

    // 1,cascade为级联。2,JPA规定 : 一的这一端为 关系被维护端。mappedBy="" 其值为 维护端的 标识。也就是
    // 用parent负责关系的维护。
    @OneToMany(cascade = { CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "parent")
    public Set<ProductType> getChildtypes() {
        return childtypes;
    }

    public void setChildtypes(Set<ProductType> childtypes) {
        this.childtypes = childtypes;
    }



1,说明:因为EJB3.0是分布式的,要通过网络传递,所以这里要序列化。。


2,如果:

 // 1,cascade为级联。2,JPA规定 : 一的这一端为 关系被维护端。mappedBy="" 其值为 维护端的 标识。也就是
    // 用parent负责关系的维护。
    @OneToMany(cascade = { CascadeType.REFRESH, CascadeType.REMOVE }, mappedBy = "parent")


这句话,写到 set()方法上去了,回报如下异常:这里都是写在 get()方法上。


Caused by: org.hibernate.MappingException: Could not determine type

for: java.util.Set, at table: ProductType, for columns:

[org.hibernate.mapping.Column(childtypes)]
    at org.hibernate.mapping.SimpleValue.getType

(SimpleValue.java:292)
    at org.hibernate.mapping.SimpleValue.isValid

(SimpleValue.java:276)
    at org.hibernate.mapping.Property.isValid(Property.java:207)
    at org.hibernate.mapping.PersistentClass.validate

(PersistentClass.java:458)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:215)
    at org.hibernate.cfg.Configuration.validate

(Configuration.java:1135)
    at org.hibernate.cfg.Configuration.buildSessionFactory

(Configuration.java:1320)
    at

org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory

(AnnotationConfiguration.java:867)
    at

org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory

(Ejb3Configuration.java:669)
    ... 61 more



3,@JoinColumn(name = "parentid")  // 此为 外键。

巴巴运动网  17   无限级产品归类的双向一对多JPA映射


巴巴运动网  17   无限级产品归类的双向一对多JPA映射

测试类:


结果成功:

巴巴运动网  17   无限级产品归类的双向一对多JPA映射