首页 > 代码库 > Hiberate CRUD操作

Hiberate CRUD操作

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

这段代码将ID设置成自动生成ID的策略,如果是自己手动创建数据库,注意要将id自动设置为auot_increment,否则将会报如下错误:

Field ‘id‘ doesn‘t have a default value

设定Id自动生成,也需要把get和set方法设置好,然后在get方法前面加上@Id,@GenratedValue来进行

============================

自动创建表

public static void main(String[] args) {          //自动创建表格,第一个true:是否显示创建表的语句。          new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);                  Student s = new Student();          s.setName("laichunbin");          s.setAge(20);          s.setAddress("hellworld");                    Configuration config = new AnnotationConfiguration();          SessionFactory sf = config.configure().buildSessionFactory();                    Session session = sf.openSession();          session.beginTransaction();          session.save(s);          session.getTransaction().commit();          session.close();                    s.setId(1);          s.setName("championl");          Session session2 = sf.openSession();          session2.beginTransaction();          session2.update(s);          session2.getTransaction().commit();          session2.close();                    //          Student s2 = new Student();//          s.setId(2);//          Session session3 = sf.openSession();//          session3.beginTransaction();//          Student g = (Student)session3.get(Student.class,1);  加载对象,通过id来获取//          Student g2 = (Student)session3.load(Student.class,4);//          System.out.println(g);//          System.out.println(g2);//          session3.getTransaction().commit();//          session3.close();              }