Hibernate

一、Hibernate概述

(开放源代码的对象关系映射框架)

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC(Java Database Connectivity,Java数据库连接)进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架。

hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的JavaEE架构中取代CMP,完成数据持久化的重任。



二、数据库连接(MVC——M)

  1. IDEA连接过程Mysql数据库:

    IntelliJ IDEA 连接数据库 详细过程

  2. 连接时可能出现的问题,原因是mysql没有设置时区:

    IDEA连接mysql又报错!Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ prope



三、Hibernate配置

  1. 新建项目时候:

    在intellij idea中使用Hibernate详细

  2. 当项目已建成时:

    可以通过File——>Project Structure——>Modules中添加Hibernate技术

    添加Hibernate配置文件:
    请添加图片描述



四、Hibernate使用

创建持久化类,反向映射工程(表转化为类):
请添加图片描述

Hibernate逻辑上屏蔽右侧,操作左侧

通过反向映射工程可以在创建的Database包下生成关于数据库中表的类

HibernateSessionFactory

Hibernate自动创建一个HibernateSessionFactory类,同样可以手动添加:

package Database;

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

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err
                    .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err
                    .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     *  return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
    public static void setConfigFile(String configFile) {
        HibernateSessionFactory.configFile = configFile;
        sessionFactory = null;
    }

    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

数据库事务操作类

在创建的Database包中新建一个OpdataDao类(数据库各种操作,事务处理):

package Database;
import Reg.*;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.*;
import java.lang.*;


public class OpdataDao {
    // sava可以将一个对象转存为数据库中的一条记录
	public void save(Object o) {
        // 从session工厂中获取一条数据库连接
		Session session = HibernateSessionFactory.getSession();
        // 事务
		Transaction transaction = null;
        // 数据库操作代码放到try
		try {
            // 开启事务
			transaction = session.beginTransaction();
            // 把对象转存为数据库中的一条记录
			session.saveOrUpdate(o);
            // 执行事务
			transaction.commit();
		} 
        //如果发生异常,将执行catch里面的代码
        catch (Exception e) {
			System.out.println("添加时发生错误----OperateDB.java" + e.toString());
			if (transaction != null) {
                // 事务回滚
				transaction.rollback();
			}
		} 
        //关闭对数据库的连接
        finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public void delete(Object o) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.delete(o);
			transaction.commit();
		} catch (Exception e) {
			System.out.println("删除时发生错误----OperateDB.java" + e.toString());
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}


	public void update(Object o) {
		Transaction transaction = null;
		Session session = HibernateSessionFactory.getSession();
		try {
			transaction = session.beginTransaction();
			session.update(o);
			transaction.commit();
		} catch (Exception e) {
			System.out.println("添加时发生错误----OperateDB.java" + e.toString());
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}


	public List select(String sql) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		List list = new ArrayList();
		try {
			transaction = session.beginTransaction();
			Query query = session.createQuery(sql);
			list = query.list();
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return list;
	}

	public List findByPage(String hql, int offset, int pageSize) {
		// 通过一个HibernateCallback对象来执行查询
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		List list = new ArrayList();
		try {
			transaction = session.beginTransaction();
			list = session.createQuery(hql).setFirstResult(offset)
					.setMaxResults(pageSize).list();
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return list;
	}


	public int getRows(String hql) {
		return select(hql).size();
	}
}

数据写库处理类

更新之前Struts2框架下的RegDeal中的代码,用于注册界面的数据处理(信息写入数据库):

package Reg;
import Database.*;

import java.util.List;

public class RegDeal {
	private String username;
	private String userpassword;
	private String email;
	private String userclass;
	private String address;
	private String showinfo;

	//写操作数据库的程序
	public String todatabase()
	{
		if("tom".equals(username))
		{
			showinfo=username+"已经注册过!";
			return "error";
		}
		else if("".equals(username)||"".equals(userpassword))
		{
			showinfo="用户名或密码不能为空!";
			return "error";
		}
		else
		{
			User u=new User();
			u.setUsername(username);
			u.setAddress(address);
			u.setEmail(email);
			u.setUserpassword(userpassword);
			u.setUserclass(userclass);

			OpdataDao op=new OpdataDao();
			String sql="from User as u where username='"+username+"'";
			List userlist=op.select(sql);

			if(userlist.size()>0){
				showinfo="用户名已注册";
				return "error";
			}else{
				op.save(u);
				return "success";
			}
		}
	}
    

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpassword() {
		return userpassword;
	}
	public void setUserpassword(String userpassword) {
		this.userpassword = userpassword;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getUserclass() {
		return userclass;
	}
	public void setUserclass(String userclass) {
		this.userclass = userclass;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
    public String getShowinfo() { 
        return showinfo; 
    }
	public void setShowinfo(String showinfo) {
		this.showinfo = showinfo;
	}
}

数据查询处理类

新建一个Log包,并创建一个LoginDeal类,用于登录界面的数据处理(在数据库中对数据进行查询等操作):

package Log;
import Database.*;
import java.util.List;

public class LoginDeal {
    private String username;
    private String userpassword;
    private String showinfo;


    public String login()
    {
        if("".equals(username)||"".equals(userpassword))
        {
            showinfo="用户名或密码不能为空!";
            return "error";
        }else{
            OpdataDao od=new OpdataDao();
            String sql="from User as u where username='"+username+"' and userpassword='"+userpassword+"'";
            String sql1="from User as u where username='"+username+"'";
            //select * from user as u where username='username' and userpassword='userpassword'
            List userlist=od.select(sql);
            List userlist1=od.select(sql1);
            if(userlist.size()>0){
                System.out.println(userlist.size());
                return "success";
            }else if(userlist.size()<=0 && userlist1.size()>0){
                showinfo="用户密码错误";
                return "error";
            }else{
                showinfo="用户不存在";
                return "error";
            }
        }
    }


    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getUserpassword() {
        return userpassword;
    }
    public void setUserpassword(String userpassword) {
        this.userpassword = userpassword;
    }
    public String getShowinfo() {
        return showinfo;
    }
    public void setShowinfo(String showinfo) {
        this.showinfo = showinfo;
    }
}


五、遇到的问题

数据库表中主键设置为自增时,可能遇到冲突问题:

org.hibernate.id.IdentifierGenerationException

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值