日期:2014-05-20 浏览次数:20684 次
/* * 实体类 */ package com.entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.hibernate.annotations.Entity; @Entity public class Weapon { private int id; private String name; @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) 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; } }
<!--添加使用hibernate注解的实体bean,而不是映射文件--> <mapping class="com/entity/Weapon" />
package com.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import com.entity.Weapon; /* * 测试类 * 通过在hibernate文件中注册实体bean,并在实体bean中添加 * hibernate注解,可以自动创建数据库中的关联表并将属性与字段关联 */ public class TestAnnotations { private static AnnotationConfiguration ac = new AnnotationConfiguration(); private static SessionFactory sf = null; public static void main(String[] args) { ac.configure(); sf = ac.buildSessionFactory(); Session session = sf.openSession(); Transaction tran = session.beginTransaction(); Weapon weapon = new Weapon(); weapon.setName("jack"); session.save(weapon); tran.commit(); session.close(); } }