hibernate里对象有三种状态:
1,Transient 瞬时 :对象刚new出来,还没设id,设了其他值。
2,Persistent 持久:调用了save()、saveOrUpdate(),就变成Persistent,有id
3,Detached 脱管 : 当session close()完之后,变成Detached。
例子程序:
Teacher类:
1 package com.oracle.hibernate.id; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 7 @Entity 8 public class Teacher { 9 10 11 12 private int id; 13 private String name; 14 15 private String title; 16 17 @Id 18 @GeneratedValue 19 public int getId() { 20 return id; 21 } 22 23 public void setId(int id) { 24 this.id = id; 25 } 26 27 public String getName() { 28 return name; 29 } 30 31 public void setName(String name) { 32 this.name = name; 33 } 34 35 public String getTitle() { 36 return title; 37 } 38 39 public void setTitle(String title) { 40 this.title = title; 41 } 42 43 44 }View Code
package com.oracle.hibernate.id; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class HibernateCoreAPITest { private static SessionFactory sf = null; @BeforeClass public static void beforeClass() { //try-chatch是为了解决Junit有错误不提示的bug try { sf = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (HibernateException e) { e.printStackTrace(); } } @Test public void testTeacher() { Teacher t = new Teacher(); //没有设id t.setName("li"); t.setTitle("high"); Session session = sf.getCurrentSession(); session.beginTransaction(); session.save(t); //打印出id System.out.println(t.getId()); session.getTransaction().commit(); } @AfterClass public static void afterClass() { sf.close(); } }