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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="">
        <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="hibernate.connection.password">*****</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@DbServer:port:sid</property>
        <property name="hibernate.connection.username">***</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        
        <mapping resource="config/mapping/oneConfig/Dbuser.hbm.xml" />
    </session-factory>
</hibernate-configuration>
  • Dbuser.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2013-10-22 15:28:34 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="pojo.oneConfig.Dbuser" table="DBUSER" >
        <id name="userId" type="int">
            <column name="USER_ID" precision="5" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="username" type="string">
            <column name="USERNAME" length="20" />
        </property>
        <property name="createdBy" type="string">
            <column name="CREATED_BY" length="20" />
        </property>
        <property name="createdDate" type="date">
            <column name="CREATED_DATE" length="7" />
        </property>
    </class>
</hibernate-mapping>
  • 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<Object[]> 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<Dbuser> 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<Dbuser> 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<Object[]> 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<String, Object> matches = new HashMap<String, Object>();
             * 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<Dbuser> 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<String, Object> row = (HashMap<String, Object>) object;
            System.out.println(row.get("USERNAME") + "," + row.get("USER_ID"));
        }*/

    }
}

改成注解的版本:

  • hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="">
        <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="hibernate.connection.password">*****</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@DbServer:port:sid</property>
        <property name="hibernate.connection.username">***</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        
        <mapping class="pojo.oneAnnotation.Dbuser" />
    </session-factory>
</hibernate-configuration>
  • 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
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,233评论 6 495
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,357评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,831评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,313评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,417评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,470评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,482评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,265评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,708评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,997评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,176评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,503评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,150评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,391评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,034评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,063评论 2 352

推荐阅读更多精彩内容

  • Hibernate: 一个持久化框架 一个ORM框架 加载:根据特定的OID,把一个对象从数据库加载到内存中OID...
    JHMichael阅读 1,963评论 0 27
  • 本文中我们介绍并比较两种最流行的开源持久框架:iBATIS和Hibernate,我们还会讨论到Java Persi...
    大同若鱼阅读 4,305评论 4 27
  • Hibernate中配置主要分为两种:一种包含了Hibernate与数据库的基本连接信息,在Hibernate工作...
    FTOLsXD阅读 2,037评论 0 10
  • 最近在看百年孤独,讲真,看不下去。即是这本书获得了诺贝尔文学奖。 我一直觉得自己是孤独的。其实,每个人都是孤独的。...
    光年123阅读 215评论 0 0
  • 今天在网上看到一篇《做有骨气的中国人 拒绝西方破节日》,让人思索回味,感慨万分。 随着改革开放的到来,西方节日随着...
    善纯阅读 1,198评论 0 3