1.在User Library 如:hibernate3.3中导入jar
hibernate-annotations-3.4.0.GA\hibernate-annotations.jar;
hibernate-annotations-3.4.0.GA\lib\ejb3-persistence.jar;
hibernate-annotations-3.4.0.GA\lib\hibernate-commons-annotations.jar
2.新建表teacher
create table teacher ( id int primary key, name varchar(20), title varchar(10) );
3.包com.fengyun.shopping.entity下建立Teacher类
package com.fengyun.shopping.entity; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Teacher { private Integer id; private String name; private String title; public Teacher() { super(); } @Id public Integer getId() { return id; } public void setId(Integer 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.cfg.xml中
<mapping class="com.fengyun.shopping.entity.Teacher"/>
4.测试
package com.fengyun.shopping.entity; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class StudentTest { public static void main(String[] args) { Student s = new Student(); s.setId(1); s.setName("wanghao"); s.setAge(12); Configuration cfg = new Configuration(); SessionFactory sf = cfg.configure().buildSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close(); sf.close(); } }
5.修改IDE配置,输入@马上出现提示
window-->perferences-->Java-->Editor-->Content Asist下设置:
Auto activation delay:100
Auto activation triggers for Java:.@
Auto activation triggers for Javadoc:#
6.如果是Annotation与XML配置文件混合使用,获得Configuration对象都要使用new AnnotationConfiguration();
异常:
org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.fengyun.shopping.entity.Teacher"/>