标签:hibernate
hibernate是根据映射文件的主键生成器生成主键哒,自己设置的主键不起作用
<!-- 主键的产生器,就该告诉hibernate容器用什么样的方式产生主键-->
<generator class="increment"></generator>
import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; public class GeneratorTest extends ConfigUtil{ /** * Hibernate: select max(pid) from Person Hibernate: insert into Person (pname, psex, pid) values (?, ?, ?) 说明: 1、主键的类型必须是数字 2、主键的生成是由hibernate内部完成的,程序员不需要干预 3、这种生成机制效率比较低 */ @Test public void testIncrement(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(); person.setPname("班长3"); person.setPsex("女"); /**save的参数必须持久化对象*/ session.save(person); transaction.commit(); session.close(); } /* * Hibernate: insert into Person (pname, psex) values (?, ?) * 说明 * 1、新的主键的产生是由数据库完成的,并不是由hibernate或者程序员完成的 * 2、该表必须支持自动增长机制 * 3、效率比较高 */ @Test public void testIdentity(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(); person.setPname("班长"); person.setPsex("女"); /** * 参数必须持久化对象 */ session.save(person); transaction.commit(); session.close(); } /** * 由程序员手写设置主键 */ @Test public void testAssigned(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(); person.setPid(4L); person.setPname("班长"); person.setPsex("女"); session.save(person); transaction.commit(); session.close(); } /** * 1、UUID是由hibernate内部生成的,主键的类型是String * 2、主键的类型必须是字符串 */ @Test public void testUUID(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(); person.setPname("班长"); person.setPsex("女"); session.save(person); transaction.commit(); session.close(); } /** * hibernate内部是根据主键生成器来生成主键的,在客户端设置主键不一定起作用,在assigned的时候起作用 */ @Test public void testIdentity_ID(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(); person.setPid(1L); person.setPname("aa"); person.setPsex("aa"); session.save(person); transaction.commit(); session.close(); } }
标签:hibernate
原文地址:http://pengya123.blog.51cto.com/8467424/1794498