zoukankan      html  css  js  c++  java
  • hibernate入门

    package com.test;
    
    
    
    import java.util.List;
    
    import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    import com.hibernate.Usertest.Usertest;
    
    public class Test {
        public static void main(String[] args) {
            String hql="from Usertest where id=?";
            String[] parm={"2"};
            List<Usertest> list=chaxun(hql,parm);
            for(Usertest u:list){
                System.out.println(u.getId()+"/"+u.getName()+"/"+u.getPassword());
            }
        }
    //添加
        public static void tianjia(Usertest um) {
            SessionFactory sf = new Configuration().configure()
                    .buildSessionFactory();
            Session s = null;
            Transaction t = null;
    
            try {
                // 准备数据
                s = sf.openSession();
                t = s.beginTransaction();
                s.save(um);
                t.commit();
            } catch (Exception err) {
                t.rollback();
                err.printStackTrace();
            } finally {
                s.close();
            }
        }
        //查询
        public static List<Usertest> chaxun(String hql,String[] parm){
            List<Usertest> list=null;
            
            SessionFactory sf = new Configuration().configure()
                    .buildSessionFactory();
            Session s = null;
            
            try {
                s = sf.openSession();
                Query query=s.createQuery(hql);
                if(parm!=null&&parm.length>0){
                    for(int i=0;i<parm.length;i++){
                        query.setString(i,parm[i]);
                    }
                }
                list=query.list();
    
            } catch (Exception e) {
                e.printStackTrace();
            
                // TODO: handle exception
            }finally{
                if(s!=null&&s.isOpen()){
                    s.close();
                }
            }
            return list;
        }
    }
    
     
    View Code
  • 相关阅读:
    调试某狐木马驱动被杀后系统卡死开机
    情景剧:C/C++中的未定义行为(undefined behavior)
    汇编概念辨析(Intel/AT&T syntax、GAS、NASM)
    软考准考证打印设置(IE1909)
    基于redis的分布式锁 RedissonLock解锁异常解决
    深入理解synchronized
    单利模式
    归并排序
    旧电脑硬盘回收
    萤石、乐橙、3D
  • 原文地址:https://www.cnblogs.com/laohan110/p/3525231.html
Copyright © 2011-2022 走看看