14hibernate hibernate的集合映射和继承映射(了解)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值