1. Annotation 的使用主要分为 2 步:
1.1 加入相应的 jar 包:
hibernate-annotations.jar // Annotation 核心包
ejb3-persistence.jar // 符合 jpa 标准的 Annotation 的实现
hibernate-commons-annotations.jar // 进行发射的时候使用
1.2 在 model 中使用 @ 注解的形式对类和属性进行注解
2. 新建hibernate_annotation ,工程结构目录如下图:
3. 加入相应的 jar 包:
2.1 加入 hibernate 相应的 jar 包 。
2.2 加入 mysql 驱动的 jar 包 。
2.3 加入支持 annotations 的 jar 包 。
2.4 如下图:
4. 代码:
4.1 Student.java
package com.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4.2 hibernate.cfg.xml
hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql://localhost/hibernate
root
root
org.hibernate.dialect.MySQLDialect
org.hibernate.cache.NoCacheProvider
true
update
4.3 StudentTest.java
package com.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.hibernate.model.Student;
public class StudentTest {
public static void main(String[] args) {
Student s = new Student(1,"s1",18);
//cfd.configure(),configure()不写参数默认查找src目录下的hibernate.cfg.xml
Configuration cfd = new AnnotationConfiguration(); //查找配置文件
//buildSessionFactory()产生一个SessionFactory工厂
SessionFactory sf = cfd.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}
}
5. 部分详解:
5.1 在 model Student.java 的类名上添加 @Entity 并引入 import javax.persistence.Entity; 使 Annotation 能够识别这是一个实体类。
5.2 在 model Student.java 的 getId() 上添加 @Id 并引入 import javax.persistence.Id; 使Annotation 能够识别并表示这是一个主键。
5.3 在 hibernate.cfg.xml 中配置 。
5.5 使用 Annotation 操作数据库步骤:
5.5.1 new 一个 AnnotationConfiguration() 对象,并调用configure() 查找配置文件 hibernate.cfg.xml 。
5.5.2 获取配置文件后通过 buildSessionFactory() 来创建 SessionFactory 。
5.5.3 通过 SessionFactory 的 openSession() 创建一个 Session 。
5.5.4 通过 Session 的 beginTransaction() 开启一个事物 。
5.5.5 调用 Session 的 save() 、update() 、delete() 等方法执行数据库操作 。
5.5.6 通过 Session 的 getTransaction() 获取当前正在操作的事物,再通过把这个事物的 commit() 将数据更新至数据库 。
5.5.7 最后关掉 Session 、 SessionFactory 。
end。
原文:http://my.oschina.net/u/1474779/blog/499167