本文以hibernate来操纵mysql数据库,所以在此之前必须确保mysql数据库已经正确安装好。。。
1、导hibernate包的核心jar包。。。
2、导hbm.xml文件
3、导hibernate.cfg.xml文件
以上三个文件为hibernate环境搭建的基础材料...其可以到hibernate的官网去下载.....在这里我为大家准备好了我自己常用的版本http://download.csdn.net/detail/caihongshijie6/6584855
4、编写pojo类(这里以Student类为例)
- package com.njupt.pojo;
- import java.io.Serializable;
- public class Student implements Serializable{
- private int id;
- private String name;
- private String pwd;
- private int age;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
5、HibernateUtil类
- package com.njupt.util;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- // 创建SessionFactory
- private static SessionFactory sessionFactory;
- // 使用静态代码块(只创建一次)来创建sessionFactory
- static{
- // 读取配置hibernate.cfg.xml
- try {
- Configuration configuration =
- new Configuration().configure("hibernate.cfg.xml");
- sessionFactory = configuration.buildSessionFactory();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 获得session
- public static Session getSession(){
- return sessionFactory.openSession();
- }
- // 关闭session,session总是默认保存数据(save(),get(),load()...)
- // 很可能出现内存泄露
- public static void close(Session session){
- if(session!=null){
- if(session.isOpen()){// null.isOpen
- session.close();
- }
- }
- }
- }
6、进行测试
编写测试类SessionTest
- package com.njupt.util;
- import java.util.Iterator;
- import java.util.List;
- import org.hibernate.Hibernate;
- import org.hibernate.HibernateException;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import org.junit.Test;
- import com.njupt.pojo.Student;
- import com.njupt.util.HibernateUtil;
- public class SessionTest {
- // public void testSave(){
- // // System.out.println("保存");
- // String str =null;
- // System.out.println(str.length());
- // }
- // 1 保存操作
- @Test
- public void testSave() {
- Session session = null;
- Transaction transaction = null;
- try {
- // 首先获得session
- session = HibernateUtil.getSession();
- // 获得Transaction
- transaction = session.getTransaction();
- // 开启事务
- transaction.begin();
- // 创建person对象
- Student person = new Student();
- person.setName("zzt_love_hjd");
- person.setAge(21);
- person.setPwd("123321");
- // 使用session保存person对象
- session.save(person);
- // 提交事务
- transaction.commit();
- } catch (Exception e) {
- // 打印异常信息
- e.printStackTrace();
- // 回滚
- transaction.rollback();
- } finally {
- // 关闭session
- HibernateUtil.close(session);
- }
- }
- // 查询id=2的person对象
- @Test
- public void testGet1() {
- Session session = null;
- // 查询操作,对数据库的表没有任何修改,不用开启事务
- try {
- session = HibernateUtil.getSession();
- // session.get()
- Student person = (Student) session.get(Student.class, 3);
- System.out.println("-------------------------------");
- System.out.println(person.getId() + "," + person.getName());
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- HibernateUtil.close(session);
- }
- }
- // 使用load加载对象
- @Test
- public void testLoad1() {
- Session session = null;
- try {
- session = HibernateUtil.getSession();
- // 没有发出sql语句
- // load():不会立刻去查询数据库,hibernate会返回一个代理对象
- // 暂时代替person对象(避免对数据库过于频繁的访问,
- // 提高系统性能)
- // hibernate 返回代理对象是cglib动态代理
- // cglib返回是目标对象(Person)的子类对象
- Student person = (Student) session.load(Student.class, 1);
- System.out.println("-------------------");
- // 真正需要访问数据的时候
- // 发出了sql语句,person发出的sql语句
- // hibernate返回的代理对象发出对应sql语句
- System.out.println(person.getName());
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- HibernateUtil.close(session);
- }
- }
- // get()查询的数据,在数据库中不存在
- // 返回null
- @Test
- public void testGet2() {
- Session session = null;
- try {
- session = HibernateUtil.getSession();
- Student person = (Student) session.get(Student.class, 2);
- System.out.println(person);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- HibernateUtil.close(session);
- }
- }
- // load()查询数据库中没有的数据
- // 如果数据库中没有与之对应的数据,则抛出
- // ObjectNotFoundException
- // 常见异常:SQLException / HibernateException / NestableRuntimeException
- @Test
- public void testLoad2() {
- Session session = null;
- try {
- session = HibernateUtil.getSession();
- Student person = (Student) session.load(Student.class, 2);
- System.out.println(person);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- HibernateUtil.close(session);
- }
- }
- // load:需要的时候才发出sql语句,去数据库中真实的查询
- // 这叫做延迟加载/懒加载(预习)
- // proxy:代理
- // org.hibernate.LazyInitializationException:
- // could not initialize proxy - no Session
- // hibernate.load()返回的代理对象的生命周期跟session保持一致
- // 关闭session,代理对象也不能使用了,不能发出sql语句
- @Test
- public void testLoad3() {
- Session session = null;
- Student person = null;
- try {
- session = HibernateUtil.getSession();
- person = (Student) session.load(Student.class, 1);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- HibernateUtil.close(session);
- }
- System.out.println(person.getName());
- }
- // 修改操作
- @Test
- public void testUpdate() {
- Session session = null;
- try {
- session = HibernateUtil.getSession();
- session.beginTransaction();// 直接开启一个事务
- Student person = (Student) session.get(Student.class, 1);
- person.setName("cangsong");
- person.setAge(30);
- session.update(person);
- // getTransaction().commit();获得开启的事务,并提交
- session.getTransaction().commit();
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- // session.getTransaction().rollback();获得开启的事务,并回滚
- session.getTransaction().rollback();
- } finally {
- HibernateUtil.close(session);
- }
- }
- // 删除操作
- @Test
- public void testDelete() {
- Session session = null;
- try {
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Student person = (Student) session.get(Student.class, 2);
- session.delete(person);
- session.getTransaction().commit();
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- session.getTransaction().rollback();
- } finally {
- HibernateUtil.close(session);
- }
- }
- // 查询t_person中所有的对象
- @Test
- public void testQuery3() {
- Session session = null;
- try {
- session = HibernateUtil.getSession();
- // createQuery("hql语句"):用session来创建一个Query对象
- // 封装hql语句
- Query query = session.createQuery("from Person");
- // 使用query做查询操作,返回的结果保存到了一个list集合当中
- List list = query.list();
- // 对集合的遍历
- Iterator<Student> iterator = list.iterator();
- while (iterator.hasNext()) {
- Student person = iterator.next();
- System.out.println(person.getId() + "," + person.getName());
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- HibernateUtil.close(session);
- }
- }
- }
经过以上的6步这时候,你便能在通过hibernate来操作数据库了................................
!!!!特别提醒:要想使用hibernate的自动建表功能,可以在hibernate.cfg.xml中按如下配置:
<property name="hbm2ddl.auto">update</property>