Hibernate--单表的增删改查

语法:
如果利用Hibernate修改数据库时,需要使用事务处理,一个事务提交时才真正将修改过的记录更新到数据库中。
1、增加记录
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();//定义事务开始
Dept dept=new Dept(new Long(1001),”math”,”shanghai”);
session.save(dept);
tran.commit(); //提交事务,真正保存到数据库中
2、 删除记录
public static void main(String[] args) {
Session session=HibernateSessionFactory.getSession();
Dept dept=(Dept)session.get(Dept.class,new Long(10));//首先查找待删除记录 通过ID
Transaction tran=session.beginTransaction();
session.delete(dept);
tran.commit();
}
3、增加,修改记录
Session session= HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
Dept dept=(Dept)session.get(Dept.class,new Long(10));
dept.setDname(“math”);
// session.save(dept);//只能进行添加—id若存在则添加失败
session.saveOrUpdate(dept);//添加或修改 —id若存在则修改:这里有Hibernate的缓存问题出现
tran.commit();
Hibernate 查询方式
Hibernate配备了一种非常强大的查询语言,这种语言看上去很像SQL。但是不要被语法结构上的相似所迷惑,HQL(Hibernate query lauguage) 被设计为完全面向对象的查询。
HQL对关键字的大写小并不区分,但是对查询的对象就要区分大小写,因为它是面向对象的查询,所以查询的是一个对象,而不是数据库的表,在sql中如果要加条件的话就是列,而在HQL里面条件就是对象的属性,而且还要给对象起别名。
1、Hibernate查询 HQL语句
限制查询结果记录数与起始记录
Session session=HibernateSessionFactory.getSession();
Query query=session.createQuery(“from Customer”);
query.setFirstResult(10); //设置查询记录开始位置,索引从0开始。
query.setMaxResults(10);//设置查询返回的最大记录个数。
List list=query.list();
注意:条件查询,用到属性,需要给值对象取别名
Session session=HibernateSessionFactory.getSession();
Query query=session.createQuery(“from Customer cus where cus.name=’zhou’”);
2、取表中部分列时
(1) 单一属性查询。还是返回一个集合,只不过集合中存储的不是表的实例而是对象。关键字不区分大小写
Session session = HibernateSessionFactory.getSession();
List cnames = session.createQuery(“select cname from Customer”).list();
for (int i=0;i< cnames.size();i++) {
String name = (String)cnames.get(i);
System.out.println(name);
}
(2) 多个属性的查询,使用对象数组。
Session session = HibernateSessionFactory.getSession();
//查询多个属性,其集合元素是对象数组
//数组元素的类型,跟实体类的属性的类型相关
List students = session.createQuery(“select sno, sname from Students”).list();
for (int i=0;i< students.size();i++) {
Object[] obj = (Object[])students.get(i);
System.out.println(obj[0] + “, ” + obj[1]);
}
(3) 多个属性的查询,使用List集合装部分列
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(“select new list(cus.name,cus.phone) from Customer cus”);
List list = query.list();
for (int i = 0; i < list.size(); i++) {
List temp=(List)list.get(i);
System.out.println(temp.get(0)); //0是索引
}
(4) 使用Map集合装部分列
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(“select new map(cus.name,cus.phone) from Customer cus”);
List list = query.list();
for (int i = 0; i < list.size(); i++) {
Map temp=(Map)list.get(i);
System.out.println(temp.get(“1”)); //”1”是key
}
(3) 条件查询,使用 ?的方式传递参数
Query query = session.createQuery(“SELECT s.id, s.name FROM Student s WHERE s.name LIKE ?”);
query.setParameter(0, “%周%”); //传递参数参数的索引是从0开始的。 如条件查询,使用”:参数”名称的方式传递参数
Query query = session.createQuery(“SELECT s.id, s.name FROM Student s WHERE s.name LIKE :myname”);
query.setParameter(“myname”, “张三”);//传递参数
因为setParameter方法返回Query接口,所以可用省略方式来查询
List students = session.createQuery(“SELECT s.id, s.name FROM Student s WHERE s.name LIKE :myname and s.id = :myid”)
setParameter(“myname”, “%周%”).setParameter(“myid”, 15).list();
5、嵌入原生sql测试
SQLQuery sqlQuery = session.createSQLQuery(“select * from t_student”);
List students = sqlQuery.list();
for (Iterator iter = students.iterator();iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + “, ” + obj[1]);
}
4、带参数的查询
(1) ?作为参数 如” from Customer cus where cus.name=?”;
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(“from Customer cus where cus.name=?”);
query.setParameter(0, “zhou”);
List list = query.list();
(2) 参数名称 :name 如” from Customer cus where cus.name=:name”;
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(“from Customer cus where cus.name=:name “);
query.setParameter(“name”, “zhou”);
List list = query.list();
Hibernate入门示例
第1步: 先建一个Java工程导入使用Hibernate最小必要包。可以到网站下载Hibernate最新的包,如果访问数据库,则需要导入数据库驱动包。最小必要包。
这里写图片描述
第2步:在src创建配置文件hibernate.cfg.xml,放置在src目录中。

<?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>
    <property name="connection.username">root</property>
    <property name="connection.url">
        jdbc:mysql://127.0.0.1:3306/hib
    </property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <property name="connection.password">1234</property>
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>

    <mapping resource="cn/hncu/domain/Student.hbm.xml" />
    <!-- 挂映射文件 -->
</session-factory>
</hibernate-configuration>

第3步:编写一个会话工厂类。通过会话工厂类产生一个会话Session对象。Session对象是Hibernate的核心。任何对数据库操作都在会话中进行的。

package cn.hncu.hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

//技术上,类似C3p0Utils
public class HibernateSessionFactory {
    private static String configFile="/hibernate.cfg.xml";//c3p0.properties
    private static Configuration config = new Configuration(); //Properties
    private static SessionFactory sessionFactory=null;//DataSource --pool

    private static ThreadLocal<Session> t = new ThreadLocal<Session>(); 

    static{
        try {
            config.configure(configFile);//加载配置文件(配置文件名可以随意取)
//          config.configure();//加载配置文件(配置文件名必须是hibernate.cfg.xml)
            sessionFactory = config.buildSessionFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Session ----Connection
    public static Session getSession() {
        Session session = t.get();
        if(session==null || !session.isOpen()){
            if(sessionFactory==null){
                rebuilSessionFactory();
            }
            session =(sessionFactory!=null)? sessionFactory.openSession():null;
            t.set(session); //放到t中
        }
        return session;
    }

    private static void rebuilSessionFactory() {
        try {

            config.configure();//加载配置文件
            sessionFactory = config.buildSessionFactory();//过时了
            //sessionFactory = config.buildSessionFactory(new StandardServiceRegistryBuilder().build());
            /*
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).build();
            sessionFactory = config.buildSessionFactory(serviceRegistry);
            */
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭与数据库的会话(连接)
    public static void closeSession() throws HibernateException{
        Session session = t.get();
        t.set(null);
        if(session!=null){
            session.close();
        }
    }

}

第4步:编写POJO类以及映射文件。
值对象–对应数据库的一个表

package cn.hncu.domain;

public class Student {
    private String studId;
    private String studName;
    private Integer age;
    private String deptId;
    public String getStudId() {
        return studId;
    }
    public void setStudId(String studId) {
        this.studId = studId;
    }
    public String getStudName() {
        return studName;
    }
    public void setStudName(String studName) {
        this.studName = studName;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getDeptId() {
        return deptId;
    }
    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }

}

Student.hbm.xml–映射文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.hncu.domain">
    <class name="Student" table="students" catalog="hib" >
        <id name="studId" type="java.lang.String">
            <column name="id" length="8"></column>
        </id>
        <property name="studName" type="java.lang.String">
            <column name="name" length="40"></column>
        </property>
        <property name="age" type="java.lang.Integer">
            <column name="age"></column>
            <!-- 如果字段名和成员变量名一样,则column可以不写 -->
        </property>
        <property name="deptId" type="java.lang.String">
            <column name="deptId" length="8"></column>
        </property>
    </class>

</hibernate-mapping>

第5步:编写测试文件
Hibernate使用语法–单表的增删改查

package cn.hncu.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.hncu.domain.Student;
import cn.hncu.hib.HibernateSessionFactory;
//完全的O,没有R
public class HibDemoJdbcDao implements HibDemoDAO{

    @Override
    public List<Student> queryAllStudents() {
        Session session=HibernateSessionFactory.getSession();
//      System.out.println("HibDemoJdbcDao---session:"+session);
        //SQL ---Structured Query Language ---面向R(关系--表)
        //HQL ---Hibernate Query Language ---面向O(值对象)
        Query query=session.createQuery("from Student");
        List<Student> students=query.list();
        return students;
    }
    //session是轻量级的,创建和销毁很容易
    @Override
    public void delStudent(Student stud) {
        //※既演示删除功能,又演示了事务的实现(测试了回滚)
        Session session=HibernateSessionFactory.getSession();
        Transaction tran=session.beginTransaction();//开启事务
        //注意,要通过完整的对象才能删除,因此要先获取该对象---2016.12.28经测试,好象不需要获取完整对象
        //stud=(Student) session.get(Student.class, stud.getStudId());
        session.delete(stud);//删除

        /* 这一段用于测试事务回滚---若数据库已经存在id为“S001”的记录,则上面的删除功作会回滚
        Student s = new Student();
        s.setStudId("S001");
        s.setStudName("Tom");
        s.setAge(25);
        s.setDeptId("D002");
        session.save(s);
        */

        tran.commit();//必须进行事务提交才会更新到数据库
        //可抓异常,可不抓
    }
    @Override
    public void addStudent(Student stud) {
        Session session=HibernateSessionFactory.getSession();
        Transaction tran=session.beginTransaction();//开启事务
//      session.save(stud);//只能进行添加---id若存在则添加失败
        session.saveOrUpdate(stud);//添加或修改 ---id若存在则修改:这里有Hibernate的缓存问题出现
        tran.commit();//必须进行事务提交才会更新到数据库
        //可抓异常,可不抓
    }
    //条件查询
    @Override
    public List<Student> queryStudents(Student stud) {
        Session session=HibernateSessionFactory.getSession();

        //清缓存
        session.clear();

        boolean f1=false,f2=false,f3=false,f4=false;
        String sql="from Student s where 1=1";
        if(stud.getStudId()!=null&&stud.getStudId().trim().length()>0){
            sql+=" and s.studId=:studId";
            f1=true;
        }
        if(stud.getStudName()!=null&&stud.getStudName().trim().length()>0){
            sql+=" and s.studName=:studName";
            f2=true;
        }
        if(stud.getAge()>0){
            sql+=" and s.age=:age";
            f3=true;
        }
        if(stud.getDeptId()!=null&&stud.getDeptId().trim().length()>0){
            sql+=" and s.deptId=:deptId";
            f4=true;
        }
//      System.out.println("sql======"+sql);
        Query query=session.createQuery(sql);
        if(f1){
            query.setParameter("studId", stud.getStudId().trim());
        }
        if(f2){
            query.setParameter("studName", stud.getStudName().trim());
        }
        if(f3){
            query.setParameter("age", stud.getAge());
        }
        if(f4){
            query.setParameter("deptId", stud.getDeptId().trim());
        }
        return query.list();
    }
}

代码:链接:http://pan.baidu.com/s/1sk8Azmd 密码:p9ux

演示功能:
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值