疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Hibernate的增删查改


 

        增加:

  //获得session

  Configuration configuration = new Configuration();

  ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()。applySettings(configuration.getProperties())。buildServiceRegistry();

  SessionFactory sessionFactory = configuration.configure()。buildSessionFactory(serviceRegistry);

  Session session = sessionFactory.openSession();

  //开启事务

  Transaction transaction = session.beginTransaction();

  //新增

  session.persist(user);//user为想要新增的对象

  //先提交事务后关闭session

  transacition.commit();

  session.close();

  删除:

  ///获得session

  Configuration configuration = new Configuration();

  ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()。applySettings(configuration.getProperties())。buildServiceRegistry();

  SessionFactory sessionFactory = configuration.configure()。buildSessionFactory(serviceRegistry);

  Session session = sessionFactory.openSession();

  //开启事务

  Transaction transaction = session.beginTransaction();

  //删除

  session.delete(user);//user为想要删除的对象

  //先提交事务后关闭session

  transacition.commit();

  session.close();

  查询(查询可不开启事务):

  //获得session

  Configuration configuration = new Configuration();

  ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()。applySettings(configuration.getProperties())。buildServiceRegistry();

  SessionFactory sessionFactory = configuration.configure()。buildSessionFactory(serviceRegistry);

  Session session = sessionFactory.openSession();

  String hql = "from User where id=:id";

  Query query = session.createQuery(hql);

  query.setParameter("id", 21);//参数

  List objectList = query.list();//转化成列表

  session.close();

  修改:

  //获得session

  Configuration configuration = new Configuration();

  ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()。applySettings(configuration.getProperties())。buildServiceRegistry();

  SessionFactory sessionFactory = configuration.configure()。buildSessionFactory(serviceRegistry);

  Session session = sessionFactory.openSession();

  //开启事务

  Transaction transaction = session.beginTransaction();

  //更新

  session.update(user);//user为想要更新的对象

  //先提交事务后关闭session

  transacition.commit();

  session.close();