zoukankan      html  css  js  c++  java
  • (惊艳)对象序列化和反序列--Hibernate的查询和新增极其相似

    Hibernate几个关键字
    持久化,ORM(关系对象映射)(数据库中关系称作是一张表)


    应用在项目中,刘一从写的查询代码,每次都挂掉,想要弄出测试数据,自己想着把查询出来的复杂数据弄到文件里

    自己要是去造那些复杂数据很麻烦
    public
    class Object1 { public static void main(String args[]){ HashMap<String, Object> obj=new HashMap<String,Object>(); obj.put("hello","String"); ArrayList<String> array = new ArrayList<String>(); array.add("abcdefg"); writeObjectToFile(array); //将这个瞬时对象写到了磁盘里面了 ArrayList<String> obj1= (ArrayList<String>) readObjectFromFile(); //和hibernate的查询代码极其相似 } public static void writeObjectToFile(Object obj) { File file = new File("D:\java\test.dat"); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); System.out.println("write object success!"); } catch (IOException e) { System.out.println("write object failed"); e.printStackTrace(); } } public static Object readObjectFromFile() { Object temp = null; File file = new File("D:\java\test.dat"); FileInputStream in; try { in = new FileInputStream(file); ObjectInputStream objIn = new ObjectInputStream(in); temp = objIn.readObject(); objIn.close(); System.out.println("read object success!"); } catch (IOException e) { System.out.println("read object failed"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return temp; }
    public static void main(String[] args) {
    
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session s = sf.openSession();
            s.beginTransaction();
                 
            Product p = new Product();
            p.setName("iphone7");
            p.setPrice(1000);
            s.save(p);   //将一个内存中的对象转到物理数据库中的一条记录
            s.getTransaction().commit();
        
            
            //根据id查询
            Product p4 = (Product)s.get(Product.class,1);

          String hql="from Product";
          List<Product> list2=(List<Product>) s.createQuery(hql).list();

     
    所有用户

    最后一个是条件查询

    以后继续,没成功,不要在这里浪费时间了

    String hql2="select * from Product where price<? ";

    @SuppressWarnings("unchecked")
    List<Product> list2=(List<Product>) s.createQuery(hql2).setParameter(0, 2000l).list();

  • 相关阅读:
    函数、对象
    webpack配置
    创智培训内容
    oracle方法
    Weblogic
    药店
    ip
    jdk账号
    ansible
    目录编码
  • 原文地址:https://www.cnblogs.com/cs-lcy/p/7554571.html
Copyright © 2011-2022 走看看