Hibernate-学习笔记02-Annotation
使用Annotation:
1、引入jar包
(1)hibernate-annotations.jar
(2)hibernate-commons-annotations.jar
(3)ejb3-persistence.jar
2、数据库建立,省略
3、配置文件
对比:
<!-- 传统 --> <mapping resource="com/ibm/hibernate/model/Student.hbm.xml"/> <!-- Annotation --> <mapping class="com.ibm.hibernate.model.Teacher"/>
代码实现:
实体类
package com.ibm.hibernate.model; import javax.persistence.Entity; import javax.persistence.Id; //Entity 为Annotation 中的注解,表明该类为实体类 @Entity public class Teacher { private int id; private String name; private String title; //标明实体类中的Primary Key @Id 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; } }
Hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> !-- 注册:告诉hibernate Model文件在哪 ,区别于传统resource=""--> <mapping class="com.ibm.hibernate.model.Teacher"/> </session-factory> </hibernate-configuration>
测试代码:
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import com.ibm.hibernate.model.Student; import com.ibm.hibernate.model.Teacher; public class TeacherTest { public static void main(String[] args) { Teacher tea = new Teacher(); tea.setId(002); tea.setName("Jude"); tea.setTitle("1"); Session session = null; SessionFactory sf = null; Transaction t = null; //1、区别与传统的配置文件,Configuration实例化的是一个AnnotationConfiguration //传统的配饰文件,Configuration实例化的是一个Configuration Configuration cfg = new AnnotationConfiguration(); sf = cfg.configure().buildSessionFactory(); session = sf.openSession(); t = session.beginTransaction(); try { session.save(tea); t.commit(); } catch (HibernateException e) { t.rollback(); e.printStackTrace(); } session.close(); sf.close(); } }