1 创建teacher 表,create table teacher (id int primary key, name varhcar(20), titlevarchar(lO));
2 创建Teacher 类
package com.wc.model;
import javax.persistence.Entity;
import javax.persistence.Id;
//注解,表明这是个实体类
@Entity
public class Teacher {
private int id;
private String name;
private String title;
//注解,表明这是主键
@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;
}
}
3 在hibernate lib 中加入annotation的jar包
a) hibernate annotaion jar
b) ejb3 persistence jar
c) hibernate common-annotations.jar
d) 注意文裆中没有提到hibernate-common-annotations.jar文件
4 参考Annotaion文档建立对应的注解
5 在hibernate.cfg.xml中建立映射<mapping class:.../〉
<mapping class="com.wc.model.Teacher"/>
6 参考文裆进行测试(注意文裆中缺少configure()的小bug)
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.wc.model.Teacher;
public class TeacherTest {
public static void main(String[] args) {
Teacher t = new Teacher();
t.setId(2);
t.setName("Wei");
t.setTitle("初级");
//创建Session对象,注意第一步是创建一个AnnotationConfiguration
Configuration cfg = new AnnotationConfiguration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
sf.close();
}
}
7 FAQ: @不给提示
a) 配置eclipse属性信息contentassist-activation--加上@