Hibernate-CRUD

  • db table
CREATE TABLE Dbuser
(
  USER_ID       NUMBER(5)    NOT NULL,
  USERNAME      VARCHAR2(20) ,
  CREATED_BY    VARCHAR2(20) ,
  CREATED_DATE  DATE  
)
  • hibernate.cfg.xml



    
        oracle.jdbc.OracleDriver
        *****
        jdbc:oracle:thin:@DbServer:port:sid
        ***
        org.hibernate.dialect.Oracle10gDialect
        
        true
        true
        
        
    

  • Dbuser.hbm.xml




    
        
            
            
        
        
            
        
        
            
        
        
            
        
    

  • POJO
package pojo.oneConfig;

import java.util.Date;

public class Dbuser {
    private int userId;
    private String username;
    private String createdBy;
    private Date createdDate;

    public Dbuser() {
    }

    public Dbuser(int userId) {
        this.userId = userId;
    }

    public Dbuser(String name, int id) {
        this.userId = id;
        this.username = name;
    }

    public Dbuser(int userId, String username, String createdBy, Date createdDate) {
        this.userId = userId;
        this.username = username;
        this.createdBy = createdBy;
        this.createdDate = createdDate;
    }

    //getter and setter

}
  • HibernateUtil
package config.hibernate.oneConfig;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}
  • Test case
package main.oneConfig;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import config.hibernate.oneConfig.HibernateUtil;
import pojo.oneConfig.Dbuser;

public class Main {

    static SessionFactory factory;

    public static void main(String[] args) {
        factory = HibernateUtil.getSessionFactory();
        
        Dbuser dbuser = new Dbuser();
        dbuser.setCreatedBy("yz20537");
        dbuser.setCreatedDate(new Date());
        dbuser.setUserId(202);
        dbuser.setUsername("hahaha");

        // add(dbuser);
        // query();
        // update(201, "aaaa");
        // delete(201);

        // testHql();

        testCriteria();

        // testNativeSql();
    }

    static void add(Dbuser dbuser) {
        Session session = factory.openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.save(dbuser);
            transaction.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            transaction.rollback();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static void query() {
        Session session = factory.openSession();
        try {
            // List result = session.createQuery("from Dbuser").list();
            List result = session.createSQLQuery("select * from dbuser").addEntity(Dbuser.class).list();
            for (Object object : result) {
                Dbuser dbuser = (Dbuser) object;
                System.out.println(String.format("%s  %s", dbuser.getUserId(), dbuser.getUsername()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static void update(int id, String name) {
        Session session = factory.openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Dbuser dbuser = (Dbuser) session.get(Dbuser.class, id);
            dbuser.setUsername(name);
            session.update(dbuser);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static void delete(int id) {
        Session session = factory.openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Dbuser dbuser = (Dbuser) session.get(Dbuser.class, id);
            session.delete(dbuser);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static void testHql() {
        Session session = factory.openSession();
        try {
            
            /*Query query = session.createQuery("from Dbuser");
            List result = query.list();
            for (Object object : result) {
                System.out.println(((Dbuser) object).getUsername());
            }*/

            /*Query query = session.createQuery("select u.username from Dbuser as u");
            List result = query.list();
            for (Object object : result) {
                System.out.println(object.toString());
            }*/
             

            
            /*Query query = session.createQuery("select u.username,u.userId from Dbuser as u");
            List result = query.list();
            for (Object[] objects : result) {
                System.out.print(objects[0].toString());
                System.out.println(objects[1].toString());
            }*/
             

            
            /*Query query = session.createQuery("select new Dbuser(u.username,u.userId) from Dbuser as u");
            List result = query.list();
            for (Dbuser i : result) {
                System.out.println(i.getUsername() + "," + i.getUserId());
            }*/
             

            
            /*Query query = session.createQuery("select new Dbuser(u.username,u.userId) from Dbuser as u where u.userId=101");
            List result = query.list();
            for (Dbuser i : result) {
                System.out.println(i.getUsername() + "," + i.getUserId());
            }*/
             

            
            /*Query query = session.createQuery("select sum(u.userId),u.username from Dbuser as u group by u.username");
            List result = query.list();
            for (Object[] objects : result) {
                System.out.print(objects[0].toString() + ",");
                System.out.println(objects[1].toString());
            }*/
             

            
            /*Query query = session.createQuery("from Dbuser");
            List result = query.setFirstResult(1).setMaxResults(2).list();// 0(no),1(yes),2(yes)
            for (Object object : result) {
                System.out.println(((Dbuser) object).getUsername());
            }*/
             
              
            
            /*Transaction transaction = session.beginTransaction();
            Query query = session.createQuery("update Dbuser as u set u.username= :username where u.userId=:userId").setParameter("username", "newName1").setParameter("userId", 101);
            int result = query.executeUpdate();
            transaction.commit();
            System.out.println(result);*/
             

            
            /*Transaction transaction = session.beginTransaction();
            Query query = session.createQuery("delete from Dbuser u where u.userId = :userId").setParameter("userId", 202);
            System.out.println(query.executeUpdate());
            transaction.commit();*/
             
        } finally {
            session.close();
        }

    }

    static void testCriteria() {

        Session session = factory.openSession();

        try {
            Criteria criteria = session.createCriteria(Dbuser.class);

            /*
             * HashMap matches = new HashMap();
             * matches.put("userId", 100); matches.put("username", "aa");
             * criteria.add(Restrictions.allEq(matches));
             */

             criteria.add(Restrictions.between("userId", 100, 101));

            // criteria.add(Restrictions.idEq(100));

            // criteria.add(Restrictions.ilike("username", "nEw%")); // like ignore case

            // criteria.add(Restrictions.in("userId", Arrays.asList(100,101)));

            // criteria.add(Restrictions.isEmpty("createdBy"));//not work @@@  Property path [yz20537.hibernate_test.Dbuser.createdBy] does not reference a collection

            // criteria.add(Restrictions.isNotEmpty("createdBy"));//not work @@@

            // criteria.add(Restrictions.isNotNull("createdBy"));

            // criteria.add(Restrictions.isNull("createdBy"));

            // criteria.add(Restrictions.sqlRestriction("CREATED_BY is null"));

            // criteria.add(Restrictions.eq("userId", 100)); // =

            // criteria.add(Restrictions.eqProperty("username", "createdBy")); //=

            // criteria.add(Restrictions.ge("userId", 100));// >=

            // criteria.add(Restrictions.geProperty("username", "createdBy")); //>=

            // criteria.add(Restrictions.gt("userId", 100));// >

            // criteria.add(Restrictions.gtProperty("username", "createdBy")); //>

            // criteria.add(Restrictions.le("userId", 100));// >=

            // criteria.add(Restrictions.leProperty("username", "createdBy")); // >=

            // criteria.add(Restrictions.lt("userId", 100));// >

            // criteria.add(Restrictions.ltProperty("username", "createdBy")); //>

            // criteria.add(Restrictions.ne("createdBy", "null")); // !=

            // criteria.add(Restrictions.neProperty("username", "createdBy"));// 字段不可为null

            // criteria.add(Restrictions.and(Restrictions.eq("username", "aa"),Restrictions.eq("userId", 1001))); //and

            // criteria.add(Restrictions.or(Restrictions.eq("username", "aa"),Restrictions.eq("userId", 1001))); // or

            // criteria.addOrder(Order.desc("username")); // order by

            // criteria.setFirstResult(0).setMaxResults(2);// pager

            
            List result = criteria.list();
            for (Dbuser dbuser : result) {
                System.out.println(dbuser.getUserId() + "," + dbuser.getUsername());
            }
             

            
              /*List result = criteria.setProjection(Projections.rowCount()).list(); 
              for (Object object : result) { 
                System.out.println((Long)object); 
              }*/
             

            
            /*List result = criteria.setProjection(Projections.avg("userId")).list();
            for (Object object : result) {
                System.out.println((Double) object);
            }*/
             

            
            /*List result = criteria.setProjection(Projections.countDistinct("userId")).list();
            for (Object object : result) {
                System.out.println((Long) object);
            }*/
             

            /*List result = criteria.setProjection(Projections.max("username")).list();
            for (Object object : result) {
                System.out.println((String) object);
            }*/
             

            /*List result = criteria.setProjection(Projections.min("userId")).list();
            for (Object object : result) {
                System.out.println((Integer) object);
            }*/
             

            /*List result = criteria.setProjection(Projections.sum("userId")).list();
            for (Object object : result) {
                System.out.println((Long) object);
            }*/ 

        } finally {
            session.close();
        }

    }

    static void testNativeSql() {
        Session session = factory.openSession();

        SQLQuery query = session.createSQLQuery("select * from Dbuser").addEntity(Dbuser.class);
        List result = query.list();
        for (Object object : result) {
            Dbuser dbuser = (Dbuser) object;
            System.out.println(dbuser.getUserId() + "," + dbuser.getUsername());
        }
         

        /*SQLQuery query = session.createSQLQuery("select username,user_id from Dbuser");
        query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        List result = query.list();
        for (Object object : result) {
            HashMap row = (HashMap) object;
            System.out.println(row.get("USERNAME") + "," + row.get("USER_ID"));
        }*/

    }
}

改成注解的版本:

  • hibernate.cfg.xml



    
        oracle.jdbc.OracleDriver
        *****
        jdbc:oracle:thin:@DbServer:port:sid
        ***
        org.hibernate.dialect.Oracle10gDialect
        
        true
        true
        
        
    

  • POJO
package pojo.oneAnnotation;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Dbuser")
public class Dbuser {
    @Id
    @Column(name = "USER_ID")
    private int userId;
    @Column(name = "USERNAME")
    private String username;
    @Column(name = "CREATED_BY")
    private String createdBy;
    @Column(name = "CREATED_DATE")
    private Date createdDate;

    public Dbuser() {
    }

    public Dbuser(int userId) {
        this.userId = userId;
    }

    public Dbuser(String name, int id) {
        this.userId = id;
        this.username = name;
    }

    public Dbuser(int userId, String username, String createdBy, Date createdDate) {
        this.userId = userId;
        this.username = username;
        this.createdBy = createdBy;
        this.createdDate = createdDate;
    }

    //getter and setter
}

你可能感兴趣的:(Hibernate-CRUD)