hibernate 常用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_33704704/article/details/86534053

保存

public void createXXX(XXX xxx) {

        Session session = null;

        try {

           session = getSession();

           Transaction tran = session.beginTransaction();

           xxx.setCommand(new String(Base64.encode(xxx.getCommand())));

           session.save(xxx);

           tran.commit();

        } catch (Exception e) {

           e.printStackTrace();

        } finally {

           if (session != null) {

               session.close();

           }

        }  

}

 

更改

public void editXXX(XXX xxx) {

        Session session = null;

        try {

           session = getSession();

           Transaction tran = session.beginTransaction();

           xxx.setCommand(new String(Base64.encode(xxx.getCommand())));

           session.saveOrUpdate(xxx);

           tran.commit();

        } catch (Exception e) {

           e.printStackTrace();

        } finally {

           if (session != null) {

               session.close();

           }

        }

}

删除

public void deleteXXX(Integer jobId) {

        Session session = null;

        try {

           session = getSession();

           String sql = "delete from xxx where jobid = '"+jobId+"'";

            System.out.println(sql);

            session.createSQLQuery(sql).executeUpdate();

        } catch (Exception e) {

           e.printStackTrace();

        } finally {

           if (session != null) {

               session.close();

           }

        }

    }

Criteria查询

 /**

     * Criteria无查询条件查询所有

     */

    public static void main(String[] args) {

        //声明一个集合用来接收结果

        List<Login> result=null;

        //声明Session

        Session session=null;

        //初始化以上对象

        try{

        session = getSession();

        //声明Criteria对象传入一个持久化类对象类型

        Criteria criteria=session.createCriteria(Login.class);

        //查询使用list方法

        result=criteria.list();

        }catch(HibernateException e){

            e.printStackTrace();

        }finally{

            session.close();

        }

        //输出结果

        for (Login login : result) {

            System.out.println("用户名:"+login.getUsername()+"   密码:"+login.getPassword()+"   年龄:"+login.getAge());

        }

}

猜你喜欢

转载自blog.csdn.net/sinat_33704704/article/details/86534053
今日推荐