由cfg.xml-->hbm.xml-->bean
执行流程(必需通过事务才能写入数据库)
Configuration对应Hibernate.cfg.xml
获得session对象:
通过以下属性就可以用getCurrentSession获得Session对象:
Session session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
--------------------------------------------------------------------------------
主键<id>的<generator class="native"/> //native"自动增加 assigned"手动
<component>一组<property> </component>
--------------------------------------------------------------------------------
set
inverse被动方,被维护
在多方(学生)inverse=true 学生被学生类维护
cascade级联即同步
--------------------------------------------------------------------------------
//自动插入数据到数据库
@Test
public void testSaveStudents(){
SessionFactory sessionFactory= HibernateSessionFactory.getSessionFactory();
Session session= sessionFactory.getCurrentSession();
Transaction tx=session.beginTransaction();
Students s1=new Students("S0000001", "张三丰", "男", "武当山", new Date());
Students s2=new Students("S0000002", "郭靖", "男", "桃花岛", new Date());
Students s3=new Students("S0000003", "黄蓉", "女", "桃花岛", new Date());
session.save(s1);
session.save(s2);
session.save(s3);
tx.commit();
sessionFactory.close();
}
查
public List<Students> queryAllStudents() {
Session session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
Transaction tx=session.beginTransaction();
String hql="from Students";
Query query=session.createQuery(hql);
List<Students> list=query.list();//查询返回列表,一行一行的
tx.commit();
return list;
增
session.save(s);//s的Students的bean类型,对应学生表的一行
删
Students students=(Students)session.get(Students.class, sid);//根据sid指定那一行
session.delete(students);//删除那一行的数据
改
session.update(students);