Hibernate--增刪改查

BtWangZhi發表於2017-08-13

1 Hibernate資料持久化,沒有和Spring整合。先從Hibernate開始理解
用到的架包:
這裡寫圖片描述
實體

public class User {
    private int id;
    private String name;
    private String pwd;
    //省略get set 方法

對映的表說明:

<hibernate-mapping>
    <class name="cn.siggy.pojo.User" table="user">
        <id name="id">
            <!-- 主鍵生成策略 -->
            <generator class="native" />
        </id>
        <!-- 實體類的屬性 -->
        <property name="name" />
        <property name="pwd" />
    </class>
</hibernate-mapping>

Hibernate配置資訊

<hibernate-configuration>
<session-factory>
    <!-- 配置資料庫資訊 -->
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="connection.url">
        jdbc:mysql://localhost:3306/hibernate?useSSL=false
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">123123</property>
    <!-- 資料庫方言 -->
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <mapping resource="cn/siggy/pojo/User.hbm.xml" />
</session-factory>
</hibernate-configuration>

增刪改查:

    public static void main(String[] args) {

    }

    /**
     * 新增
     */
    public static void save01() {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();// 開啟事務
        User user = new User();
        user.setName("張三瘋");
        user.setPwd("1111");
        session.save(user);// 儲存
        transaction.commit();// 提交
        session.close();
        System.out.println("run over");
    }

    /**
     * 刪除,通過load方式獲取然後刪除
     */
    public static void delete01() {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        User user = (User) session.load(User.class, 11);// 當資料不存在時,會丟擲異常
        session.delete(user);
        transaction.commit();
        session.close();
        System.out.println("run over");
    }

    /**
     * 刪除,get方式獲取然後刪除
     */
    public static void delete02() {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        User user = (User) session.get(User.class, 12);// 當資料不存在時,不會丟擲異常
        session.delete(user);
        transaction.commit();
        session.close();
        System.out.println("run over");
    }

    /**
     * 刪除,通過主鍵構造一個物件然後刪除
     */
    public static void delete03(){
        Session session=getSession();
        Transaction transaction=session.beginTransaction();
        User user=new User();
        user.setId(13);
        session.delete(user);
        transaction.commit();
        session.close();
        System.out.println("run over");
    }

    /**
     * 更新,不能選擇性更新
     */
    public static void update01(){
        Session session=getSession();
        Transaction transaction=session.beginTransaction();
        User user=new User();
        user.setId(14);
        user.setPwd("22211");//不需要更新的資料自動為空,沒有選擇性更新
        session.update(user);
        transaction.commit();
        session.close();
        System.out.println("run over");
    }

    /**
     * 更新,能選擇性的更新資料
     */
    public static void update02(){
        Session session=getSession();
        Transaction transaction=session.beginTransaction();
        User user=(User)session.get(User.class, 14);
        System.out.println("1"+user.getName());
        user.setName("dema");
        session.update(user);
        transaction.commit();
        session.close();
        System.out.println("run over");
    }

    /**
     * 查詢,使用HQL,不分頁
     */
    public static void query01() {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("from User");
        List<User> lst = query.list();
        System.out.println("資料條數:"+lst.size());
        System.out.println();
        for (User user : lst) {
            System.out.println(user.getId()+" "+user.getName()+" "+user.getPwd());
        }
        transaction.commit();
        session.close();
        System.out.println("run over");
    }   

    /**
     * 查詢,使用HQL,分頁
     */
    public static void query02(){
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        Query query=session.createQuery("from User");
        query.setFirstResult(0);//設定從第幾個開始查
        query.setMaxResults(10);//設定條數
        List<User> lst = query.list();
        System.out.println("資料條數:"+lst.size());
        for (User user : lst) {
            System.out.println(user.getId()+" "+user.getName()+" "+user.getPwd());
        }
        transaction.commit();
        session.close();
        System.out.println("run over");
    }

    public static void query(){
        StringBuffer sqlStr = new StringBuffer();
        sqlStr.append("select id,no,name,pwd");
        SQLQuery query = (SQLQuery) getSession().createSQLQuery(sqlStr.toString());
        List<Object[]> lstObjArr = query.list();
        for(Object[] objArr:lstObjArr){
            for(Object obj:objArr){
                System.out.print(obj+"  ");
            }
            System.out.println();
        }
        System.out.println("run over");
    }

    /**
     * 獲取SessionFactory
     * @return
     */
    private static Session getSession(){
        // 1新建Configuration物件
        //Configuration cfg=new Configuration().configure();
        Configuration cfg=new Configuration().configure();
        // 2通過Configure建立SessionFactory物件
        /*SessionFactory sf=cfg.buildSessionFactory();*/
        /* ServiceRegistry sr=new ServiceRegistryBuilder().appl */

        ServiceRegistry registry=new StandardServiceRegistryBuilder()
         .applySettings(cfg.getProperties()).build(); 
        SessionFactory sessionFactory=cfg.buildSessionFactory(registry);
        return sessionFactory.openSession();
    }

相關文章