一、在数据库中创建teacher表(数据库hibernate)
create table teache( id int auto_increment primary key, name varchar(20), title varchar(20) );
二、创建model
在cn.orlion.hibernate.model下创建实体类Teacher(注意添加注解,一开始只添加了@Id,然后抛出异常,后来又加上了@GeneratedValue(strategy = GenerationType.AUTO))
package cn.orlion.hibernate.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Teacher{ private int id; private String name; private String title; @Id @GeneratedValue(strategy = GenerationType.AUTO) 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; } }
三、在配置文件中配置类:
在hibernate.cfg.xml中添加下面一行
<mapping class="cn.orlion.hibernate.model.Teacher" />
OK,配置完成写一个测试:
package cn.orlion.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import cn.orlion.hibernate.model.Teacher; public class TeacherTest { public static void main(String[] args){ Teacher t = new Teacher(); t.setName("test1"); t.setTitle("title1"); 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(); } }
运行可以看到数据库中添加了一条记录。
原文:http://www.cnblogs.com/orlion/p/5040438.html