1.Set(参考前面的实例)
2.List//支持排序
a.OrderBy
public class Group
{
private int id;
private String name;
@OneToMany(mappedBy="group",
cascade={CascadeType.All})
@OrderBy("name ASC")//默认按照主键排序
private List<User> users = new ArrayList<User>();
}
3.Map
a.@Mapkey
public class Group
{
private int id;
private String name;
@OneToMany(mappedBy="group",
cascade={CascadeType.All})
@Mapkey(name="id")//指明key是哪个字段
private Map<Integer,User> users = new HashMap<Integer,User>();
}
public void testLoadGroup(){
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
Group p = (Group)s.load(Group.class,1);
for(Map.Entry<Integer,User> entry:g.getUsers.entrySet()){
System.out.println(entry.getValue().getName());
}
s.getTransaction().commit();
}
4.继承映射的三种方式
a.一张总表single_table(最简单)
用一个字段discriminator来区分对象
缺点:造成大量空的冗余字段
表结构--
T_Person:
id
name
score
title
discriminator
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="discriminator",discriminatorType=DiscriminatorType.String)
@DiscriminatorValue("person")
public class Person
{
private int id;
private String name;
}
@Entity
@DiscriminatorValue("student")
public class Student extends Person
{
private int score;//不要在子类里写id
}
@Entity
@DiscriminatorValue("teacher")
public class Teacher extends Person
{
private String title;
}
b.每个类分别一张表table_per_class
没有父表,多态查询时多表union
缺点:不同表之间的id值不可重复,id生成策略复杂
表结构--
T_Person:
id
name
T_Student:
id
name
score
T_Teacher:
id
name
title
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@TableGenerator(
name="t_gen",
table="t_gen_table",
pkColumnName="t_pk",
valueColumnName="t_value",
pkColumnValue="person_pk",
initialValue=1,
allocationSize=1
)
public class Person
{
@Id
@GeneratedValue(generator="t_gen",strategy=GenerationType.TABLE)
private int id;
private String name;
}
@Entity
public class Student extends Person
{
private int score;
}
@Entity
public class Teacher extends Person
{
private String title;
}
c.每个子类一张表joined(较常用)
父表中保存共有属性,父表和子表用主键连接
缺点:要查询一个对象的完整信息,必须多表连接
内部采用case when来具体区分子类
表结构--
T_Person_S:
id
name
T_Student_S:
id
score
T_Teacher_S:
id
title
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person
{
private int id;
private String name;
}
@Entity
public class Student extends Person
{
private int score;//子类表的id不要自动生成
//要参考父表的id
}
@Entity
public class Teacher extends Person
{
private String title;
}