Hibernate注释的映射问题

时间:2014-06-04 17:45:34

标签: java hibernate orm hibernate-mapping hibernate-annotations

enter image description here

我有上面的表我需要用注释编写HIbernate实体类 和映射

我在获取ObjectAttributes列表时遇到问题..

类编写如下

@Entity
public class Object {
    @Id
    private int id;

    private String name;

    @OneToMany(mappedBy="object",fetch=FetchType.LAZY)
    private List<ObjectAttribute> attrubuteList;
}

@Entity
public class ObjectAttribute {
    @Id
    private int id;
    @ManyToOne
    @JoinColumn(name="objectId")
    private Object object;
    private String name;
}

@Entity
public class Filter {
    @Id
    private int filterId;
    @ManyToOne
    @JoinColumn(name="ObjectId")
    private Object object;
    private String filterName;
    @OneToMany(mappedBy="filter")
    private Set<FilterAttribute> filterValues;
}

@Entity
public class FilterAttribute implements Serializable {

    @Id
    private int filterAttrId;
    @Id
    @ManyToOne
    @JoinColumn(name="objectId")
    private Object object;
    @Id
    @ManyToOne
    @JoinColumn(name="filterId")
    private Filter filter;
    @Id
    @ManyToOne
    @JoinColumn(name="attributeId")
    private ObjectAttribute attribute;

    private String value;
}

注意没有添加getter和setter

并测试代码如下

List<Object> list = sess.createCriteria(Object.class).list();
        for(Object ob: list)
        {
            System.out.println("Object name : "+ ob.getName());
            List<ObjectAttribute> attList = ob.getAttrubuteList();

            for (Iterator iterator = attList.iterator(); iterator.hasNext();) {
                ObjectAttribute objectAttribute = (ObjectAttribute) iterator
                        .next();
                System.out.println(objectAttribute.getName());
            }
        }

attList = ob.getAttrubuteList();返回null

1 个答案:

答案 0 :(得分:0)

在我的测试代码中创建Object,如下所示

    Object obj = new Object();
    obj.setId(1);
    obj.setName("Employee");
    sess.save(obj);

    ObjectAttribute ageAtt = new ObjectAttribute();
    ageAtt.setId(1);
    ageAtt.setName("age");
    ageAtt.setObject(obj);
    sess.save(ageAtt);

    ObjectAttribute depAtt = new ObjectAttribute();
    depAtt.setId(2);
    depAtt.setName("department");
    depAtt.setObject(obj);
    sess.save(depAtt);

    ObjectAttribute attName = new ObjectAttribute();
    attName.setId(3);
    attName.setName("name");
    attName.setObject(obj);
    sess.save(attName);

我没有添加这些行

obj.getAttrubuteList().add(depAtt);
        obj.getAttrubuteList().add(attName);
        obj.getAttrubuteList().add(ageAtt);

但我不知道为什么我们需要这样做!!