容器实体内的 Hibernate 映射集合
Hibernate mapping collection inside container entity
我有以下 class 结构:
public class Container {
private Set<Child> childs = new HashSet<>();
}
public class Child {
String name;
String value;
String param;
}
因为容器 class 在应用程序中将是单一的(只是可能更新的集合的包装器),我想将它存储在单一的 table 中,例如 "childs" 列
id | name | value | param
是否可以做这样的映射以便在fetch或
通过 hb session 存储它,并相应更新 childs 集合:
getSession().saveOrUpdate(container)
如果是这样,在那种情况下应该是什么映射?
UPD:我打算将 2 classes 映射到单个 table
我不确定 getSession().saveOrUpdate(container) ,但是您问题的映射应该是这样的。
@Entity
public class Container {
@ManyToOne
private Set<Child> childs = new HashSet<>();
}
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
String value;
String param;
}
经过一些研究,我最终得到了这样的解决方案:
@Entity
@Table(name = "childs")
public class Container {
@Id
//optional your id strategy
@GeneratedValue(strategy = GenerationType.AUTO, generator = "xyz")
Long id;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="childs", joinColumns=@JoinColumn(name="id"))
private Set<Child> childs = new HashSet<>();
}
@Embeddable
public class Child {
String name;
String value;
String param;
}
table 结构 - childs(id, name, value, param)
我有以下 class 结构:
public class Container {
private Set<Child> childs = new HashSet<>();
}
public class Child {
String name;
String value;
String param;
}
因为容器 class 在应用程序中将是单一的(只是可能更新的集合的包装器),我想将它存储在单一的 table 中,例如 "childs" 列
id | name | value | param
是否可以做这样的映射以便在fetch或 通过 hb session 存储它,并相应更新 childs 集合:
getSession().saveOrUpdate(container)
如果是这样,在那种情况下应该是什么映射?
UPD:我打算将 2 classes 映射到单个 table
我不确定 getSession().saveOrUpdate(container) ,但是您问题的映射应该是这样的。
@Entity
public class Container {
@ManyToOne
private Set<Child> childs = new HashSet<>();
}
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
String value;
String param;
}
经过一些研究,我最终得到了这样的解决方案:
@Entity
@Table(name = "childs")
public class Container {
@Id
//optional your id strategy
@GeneratedValue(strategy = GenerationType.AUTO, generator = "xyz")
Long id;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="childs", joinColumns=@JoinColumn(name="id"))
private Set<Child> childs = new HashSet<>();
}
@Embeddable
public class Child {
String name;
String value;
String param;
}
table 结构 - childs(id, name, value, param)