实体类:
import javax.persistence.Entity; import javax.persistence.Id; @Entity public class foo { private int id; private String name; private String total; @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 getTotal() { return total; } public void setTotal(String total) { this.total = total; } }
特别要注意配置文件的申请,一般是:
<mapping resource="com/model/foo.hbm.xml"/>
使用Annotation 注解形式就要写成:
<mapping class = "com.model.foo.hbm.xml"/>
还有在实例化的时候,要写成:
Configuration configuration = new AnnotationConfiguration();
只有AnnotationConfiguration可以认识注解形式的实体类。
完整调用类:
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class test1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub foo s = new foo; s.setId(1); s.setName(2); S.settotal(ss); Configuration configuration = new AnnotationConfiguration(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); //用事务方式储存\ session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close(); //sessionFactory也要关闭 sessionFactory.close(); } }
时间: 2024-09-27 19:41:10