首页 > Web开发 > 详细

hibernate之crud&hql&分页

时间:2016-10-16 13:50:21      阅读:263      评论:0      收藏:0      [点我收藏+]
技术分享
package com.eudask.ht1;

import java.util.Date;

public class Stu {
    private Integer id;
    private String xm;
    private String sex;
    private Date sr;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getXm() {
        return xm;
    }
    public void setXm(String xm) {
        this.xm = xm;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getSr() {
        return sr;
    }
    public void setSr(Date sr) {
        this.sr = sr;
    }
    @Override
    public String toString() {
        return "Stu [id=" + id + ", xm=" + xm + ", sex=" + sex + ", sr=" + sr
                + "]";
    }
    

}
Stu.java
技术分享
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping
    package="com.eudask.ht1">
    
    <class name="com.eudask.ht1.Stu" table="stu">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="xm"  column="xm"/>
        <property name="sex" type="java.lang.String" column="sex"/>
        <property name="sr" type="java.util.Date" column="sr"/>
            
    </class>
    
    

</hibernate-mapping>
Stu.hbm.xml
技术分享
package com.eudask.ht1.test;


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

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import com.eudask.ht1.Stu;
import com.eudask.ht1.util.HibernateUtil;

public class TestSt {

    @Test
    public void addStu() {
        Stu stu = new Stu();
        stu.setXm("郭德纲2");
        stu.setSex("男2");
        stu.setSr(Date.valueOf("2016-10-21"));

        // 获取session
        Session session = HibernateUtil.getSession();
        // 开启事务
        Transaction ts = session.beginTransaction();
        try {
            session.save(stu);
            ts.commit();
        } catch (Exception e) {
            e.printStackTrace();
            ts.rollback();
        } finally {
            session.close();
        }
    }
    @Test
    public void testCritetoa(){
        // 获取session
        Session session = HibernateUtil.getSession();
        Criteria cr=session.createCriteria(Stu.class);
        cr.add(Restrictions.eq("id",1));
        List<Stu> Stus=cr.list();
        for(Stu stu:Stus){
            System.out.print(stu);
        }
        session.close();
        
    }
    
    @Test
    public void testSql(){
        // 获取session
        Session session = HibernateUtil.getSession();
        String sql="select * from stu";
        SQLQuery SQ=session.createSQLQuery(sql);
        List<Object[]> Stus=SQ.list();
        for(Object[] stu:Stus){
            for(Object stuo:stu){
                System.out.println(stuo);
            }
        }
        session.close();
        
    
        
    }
    
    // 根据id查询数据
        @Test
        public void findById() {
            Session session = HibernateUtil.getSession();
            Stu stu = (Stu) session.get(Stu.class, 1);
            System.out.println(stu.getId());
            System.out.println(stu.getSex());
            System.out.println(stu.getXm());
            System.out.println(stu.getSr());
            session.close();
        }

        
        // 修改数据
        @Test
        public void update() {
            Session session = HibernateUtil.getSession();
            Stu stu = (Stu) session.get(Stu.class, 1);
            // 开启事务
            Transaction ts = session.beginTransaction();
            try {
                stu.setXm("岳云鹏");
                session.update(stu);
                ts.commit();
            } catch (Exception e) {
                e.printStackTrace();
                ts.rollback();
            } finally {
                session.close();
            }
        }

        
        // 查询所有
        @Test
        public void selectAll() {
            //获得HibernateSession对象
            Session session = HibernateUtil.getSession();
            //编写HQL语句
            String hql = "from Stu where id=:input";
//            String hql = "from Stu as s where id=?";
            //以hql语句做为参数调用session的createQuery创建Query对象
            Query query = session.createQuery(hql);
            //如果有参数通过query.setXX()方法 设置查询条件
            query.setInteger("input", 1);
//            query.setInteger(0, 1);
            //通过query的list等方法遍历查询结果
            List<Stu> stus = query.list();
            for (Stu s : stus) {
                System.out.println(s);
            }
            session.close();
        }

        
        // 删除
        @Test
        public void delete() {
            Session session = HibernateUtil.getSession();
            Stu stu = (Stu) session.get(Stu.class, 2);
            Transaction ts = session.beginTransaction();
            try {
                session.delete(stu);
                ts.commit();
            } catch (Exception e) {
                e.printStackTrace();
                ts.rollback();
            } finally {
                session.close();
            }
        }
        
        
        //分页of hibernate
        public void fenye(int page,int pageItems){
            Session session = HibernateUtil.getSession();
            String hql="from Stu";
            Query query=session.createQuery(hql);
            query.setFirstResult((page-1)*pageItems);
            query.setMaxResults(pageItems);
            List<Stu> list=query.list();
            for(Stu stu:list){
                System.out.println(stu);
            }
            
        }
        
        public static void main(String[] args) {
            TestSt t=new TestSt();
            t.fenye(1, 10);
            System.out.println("=======================");
            t.fenye(2, 10);
        }
}
TestSt.java
技术分享
package com.eudask.ht1.util;

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

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    static{
        //加载hibernate主配置文件
//        Configuration confg=new Configuration().configure();
        Configuration confg=new Configuration();
        confg.configure();
        sessionFactory=confg.buildSessionFactory();
    }
    
    //创建session
    public static Session getSession(){
        return sessionFactory.openSession();
    }

}
HibernateUtil.java
技术分享
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="foo">
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql:///hibernate_20120328</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="hibernate.connection.password">hyy</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">false</property>
        <!-- 
            create:先删除,再创建
            update:如果表不存在就创建,不一样就更新,一样就什么都不做。
            create-drop:初始化时创建表,SessionFactory执行close()时删除表。
            validate:验证表结构是否一致,如果不一致,就抛异常。
         -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 
            设置默认的事务隔离级别:
            隔离级别        对应的整数表示
            READ UNCOMMITED    1
            READ COMMITED    2
            REPEATABLE READ    4
            SERIALIZEABLE    8
         -->
        <property name="connection.isolation">2</property>
    <mapping resource="com/eudask/ht1/Stu.hbm.xml" />
    <mapping resource="com/eudask/ht1/Tea.hbm.xml"/>
    <mapping resource="com/eudask/ht1/Qiang.hbm.xml"/>

</session-factory>
</hibernate-configuration>
hibernate.cfg.xml

 

hibernate之crud&hql&分页

原文:http://www.cnblogs.com/huangyongyong/p/5966365.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!