hibernate學習:HelloWorld_Annotation

十五樓亮哥發表於2015-02-05

一:HelloWorld註解實現



二:程式原始碼

@Entity
public class Teacher {
	@Id
	private int id;

	private String name;

	private String title;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

}



<?xml version='1.0' encoding='utf-8'?>


com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/hibernaterootrootorg.hibernate.dialect.MySQLDialect org.hibernate.cache.NoCacheProvidertrueupdate




public class TeacherTest {
	public static void main(String[] args) {
		Teacher t = new Teacher();
		t.setId(1);
		t.setName("劉彥亮");
		t.setTitle("中級");

		Configuration cfg = new AnnotationConfiguration();
		// 解析hibernate配置檔案cfg.configure()
		// buildSessionFactory建立session工廠
		SessionFactory factory = cfg.configure().buildSessionFactory();
		//建立session
		Session session = factory.openSession();
		//開啟事務
		session.beginTransaction();
		//持久化操作
		session.save(t);
		//提交事務
		session.getTransaction().commit();
		//關閉相關資源
		session.close();
		factory.close();

	}

}

三:Console輸出

Hibernate: insert into Teacher (name, title, id) values (?, ?, ?)

四:知識總結

  與 HibernateHelloWorld_xml不用的是:
(1)model中使用了@Entity @Table @id @Column等註解,對映跟表的關係

(2)Hibernate配置檔案中對映實體,用class屬性
   <mapping class="com.hibernate.model.Teacher" />

  (3)單元測試中,解析配置檔案的時候,用的是AnnotationConfiguration
Configuration cfg = new AnnotationConfiguration();

相關文章