gpt4 book ai didi

java - Hibernate 注释上的映射问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:48:53 24 4
gpt4 key购买 nike

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

最佳答案

在我的测试代码中创建对象时,如下所示

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

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

关于java - Hibernate 注释上的映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com