hibernate的几种主键

 
public class generator extends hibernateUtil {

	/*
	 * increment机制是int 查找当前id的最大值加1,两次查询效率底点
	 * Hibernate: select max(id) from Person
      Hibernate: insert into Person (name, id) values (?, ?)
	 */
	@Test
	public void testIncrement()
	{
		Session session = factory.openSession();
		Transaction tran = session.beginTransaction();
		Person p = new Person();
		p.setName("yyyyy");
		session.save(p);
		tran.commit();
		session.close();
	}
	
	/*
	 * Hibernate: insert into Person (name, id) values (?, ?)
	 *   1;表必须支持自动增长机制 在Mysql中加入autoincrement
	 *   2;主键的产生是数据库产生的,并不是由hibernate产生的
	 *   3:比increment效率高 
	 */
	@Test
	public void testIdentity()
	{
		Session session = factory.openSession();
		Transaction tran = session.beginTransaction();
		Person p = new Person();
		p.setName("zzzzz");
		session.save(p);
		tran.commit();
		session.close();
	}
	
	/*
	 * assigned产生机制
	 * 由程序员手动添加id,一般测试的时候用,企业里面用的少
	 */
	@Test
	public void testAssigned()
	{
		Session session = factory.openSession();
		Transaction tran = session.beginTransaction();
		Person p = new Person();
		p.setName("zzzzz");
		p.setId("222");
		session.save(p);
		tran.commit();
		session.close();
	}
	
	/*
	 * UUID是hibernate内部生产的
	 * id 必须是字符串类型的 
	 * Hibernate: insert into Person (name, id) values (?, ?)
	 */
	@Test
	public void testUUID()
	{
		Session session = factory.openSession();
		Transaction tran = session.beginTransaction();
		Person p = new Person();
		p.setName("QQQQQ");
		session.save(p);
		tran.commit();
		session.close();
	}
}

 

posted @ 2015-05-11 18:57  BigShui  阅读(209)  评论(0编辑  收藏  举报