Hibernate核心组件入门

Hibernate核心组件入门

在Hibernate开发中关键一点就是使用Hibernate的核心类和接口,它位于业务层和持久化层之间,它除了核心组件外还包括它的配置文件(hibernate.cfg.xml或者hibernate.properties),映射文件(XXX.hbm.xml)和持久化对象。

1:Configuration

主要负责配置并且启动hibernate,创建SessionFactory对象,在启动的时候,Configuration首先定位到映射文件的位置,读取配置,然后创建sessionFactory对象。

2:SessionFactory

负责初始化Hibernate,它充当数据存储源的代理,并且负责创建session对象,这里用到了工厂的模式,SesionFactory不是轻量级的,所以一个项目就需要一个SessionFactory,当需要多次操作数据库的时候,可以为每一个数据库制定一个sessionfactory线程对象,sessionfactory是产生session的工厂。

3:Session

负责执行持久化对象的操作它用get(),load(),save(),update()delete()等方法对PO进行加载,保存更新及删除等操作。Session对象是非线程安全的。

4:Transaction

管理Hibernate的事务,它的主要的方法是commit(),和rollback().Session的beginTransation()方法可以生成该对象。

5:Query

负责各种数据库的查询,可以使用HQL语言对PO进行查询操作,Query对象可以由Session的createQuery的方法生成。

下面是一个简单的基于Struts-Hibernate的登录注册系统:

1:首先需要引入需要的架包

2:编写web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

3:还需要写一个struts.xml文件,这个文件是处理逻辑的和数据库的hibernate.cfg.xml文件

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    
    <package name="default" extends="struts-default">
       <action name="login" class="action.LoginAction">
            <result name="success">/success.jsp</result>
            <result name="input">/login.jsp</result>
            <result name="error">/login.jsp</result>
        </action>
        <action name="register" class="action.RegisterAction">
            <result name="success">/login.jsp</result>
            <result name="input">/register.jsp</result>
            <result name="error">/register.jsp</result>
        </action>
    </package>
</struts>
<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_loginRegis</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>    
    <mapping resource="PO/UserInfoPO.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

4:编写登录的界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@taglib prefix="s" uri="/struts-tags" %><!-- 引入struts标签 -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>SH登录和注册系统</title>
</head>
<body bgcolor = "green">
<s:form action="login" method="post">
<br><br><br><br><br><br>
<table border = "1" align="center" bgcolor="red">
<tr>
<td><s:textfield name="userName" label="用户名" size="16"></s:textfield>      </td>

</tr>

<tr>
<td><s:textfield name="password" label="用户密码" size="16"></s:textfield>      </td>

</tr>

<tr>
<td colspan="2" align="left"> <s:submit value="登录"></s:submit>                   </td>

</tr>


<tr>
<td colspan = "2" align = "center">

<s:a href ="http://localhost:8080/SH_Login/register.jsp">注册</s:a>
</td>

</tr>



</table>



</s:form>

</body>
</html>

注册界面:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
       
    </head>
    <body bgcolor="#CCCCFF">
        <s:form action="register" method="post">
            <br><br><br><br><br><br>
            <table border="1" align="center" bgcolor="red">
                <tr>
                    <td>
                        <s:textfield name="userName" label="用户名字" size="16"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        <s:password name="password1" label="用户密码" size="18"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        <s:password name="password2" label="再次输入密码" size="18"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="提交"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <input type="reset" value="清空"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <s:a href="/login.jsp">返回</s:a>
                    </td>
                </tr>
            </table>
        </s:form>
    </body>
</html>

工具类:

package Util;

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

public class HibernateSessionFactory {
    private SessionFactory sessionFactory;
    public HibernateSessionFactory(){
    }
    public SessionFactory config(){
        try{
            Configuration configuration=new Configuration();
            Configuration configure = configuration.configure("hibernate.cfg.xml");
            return configure.buildSessionFactory();
        }catch(Exception e){
            e.getMessage();
            return null;
        }
    }
    public Session getSession(){
        sessionFactory=config();
        return sessionFactory.openSession();
    }
}

action业务逻辑处理

package action;




import com.opensymphony.xwork2.ActionSupport;

import Dao.LoginRegisterInfo;
import PO.UserInfoPO;

import java.util.List;

public class LoginAction extends ActionSupport{
    private String userName;
    private String password;
    private String message="error";
    private List list;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void validate(){
        if(this.getUserName()==null||this.getUserName().length()==0){
            addFieldError("userName","用户名不能为空!");
        }else{
            LoginRegisterInfo info=new LoginRegisterInfo();
            list=info.queryInfo("userName", this.getUserName());
            if(list.size()==0){
                addFieldError("userName","该用户尚未注册!");
            }else{
                UserInfoPO ui=new UserInfoPO();
                int count=0;
                for(int i=0;i<list.size();i++){
                    count++;
                    ui=(UserInfoPO)list.get(i);
                    if(this.getUserName().equals(ui.getUserName())){
                        if(ui.getPassword().equals(this.getPassword())){
                            message="success";
                        }else{
                            addFieldError("password","登录密码不正确!");
                        }
                    }
                }
            }
        }
    }
    public String execute() throws Exception{
        return message;
    }
}
package action;



import PO.UserInfoPO;
import com.opensymphony.xwork2.ActionSupport;
import Dao.LoginRegisterInfo;
import java.util.List;

public class RegisterAction extends ActionSupport{
    private String userName;
    private String password1;
    private String password2;
    private String mess="error";
    private List list;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName= userName;
    }
    public String getPassword1() {
        return password1;
    }

    public void setPassword1(String password1) {
        this.password1 = password1;
    }
    public String getPassword2() {
        return password2;
    }
    public void setPassword2(String password2) {
        this.password2 = password2;
    }
    public void validate(){
        if(this.getUserName()==null||this.getUserName().length()==0){
            addFieldError("userName","用户名不能为空!");
        }else{
            LoginRegisterInfo info=new LoginRegisterInfo();
            list=info.queryInfo("userName", this.getUserName());
            UserInfoPO ui=new UserInfoPO();
            for(int i=0;i<list.size();i++){
                ui=(UserInfoPO)list.get(i);
                if(ui.getUserName().equals(this.getUserName())){
                    addFieldError("userName","用户名已存在!");
                }
            }
        }
        if(this.getPassword1()==null||this.getPassword1().length()==0){
            addFieldError("password1","登录密码不允许为空!");
        }else if(this.getPassword2()==null||this.getPassword2().length()==0){
            addFieldError("password2","重复密码不允许为空!");
        }else if(!this.getPassword1().equals(this.getPassword2())){
            addFieldError("password2","两次密码不一致!");
        }
    }
    public UserInfoPO userInfo(){
        UserInfoPO info=new UserInfoPO();
        info.setUserName(this.getUserName());
        info.setPassword(this.getPassword1()); 
        return info;
    }
   public String execute() throws Exception{
        LoginRegisterInfo lr=new LoginRegisterInfo();
        String ri=lr.saveInfo(userInfo());
        if(ri.equals("success")){
            mess="success";
        }
        return mess;
    }
}

Dao的编写:

package Dao;

import Util.HibernateSessionFactory;
import PO.UserInfoPO;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class LoginRegisterInfo {
   private Session session;
    private Transaction transaction;
    private Query query;
    HibernateSessionFactory getSession;
    public LoginRegisterInfo(){
    }
    public String  saveInfo(UserInfoPO info){
        String mess="error";
        getSession=new HibernateSessionFactory();
        session=getSession.getSession();
        try{
            transaction=session.beginTransaction();
            session.save(info);
            transaction.commit();
            mess="success";
            return mess;
        }catch(Exception e){
            message("RegisterInfo.error:"+e);
            e.printStackTrace();
            return null;
        }
    }
    public List queryInfo(String type,Object value){
        getSession=new HibernateSessionFactory();
        session=getSession.getSession();
        try{
            String hqlsql="from UserInfoPO as u where u.userName=?";
            query=session.createQuery(hqlsql);
            query.setParameter(0, value);
            List list=query.list();
            transaction=session.beginTransaction();
            transaction.commit();
            return list;
        }catch(Exception e){
            message("LoginRegisterInfo类中有异常,异常为:"+e);
            e.printStackTrace();
            return null;
        }
    }
    public void message(String mess){
        int type=JOptionPane.YES_NO_OPTION;
        String title="提示信息";
        JOptionPane.showMessageDialog(null, mess, title, type);
    }
}

 

映射文件:

<?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>
  <class  name="PO.UserInfoPO" table="info" catalog="db_loginRegis">
    <id name="id" type="int">
      <column name="id"/>
      <generator class="native"/>
    </id>
    <property name="userName" type="string">
      <column name="userName" length="30" not-null="true"/>
    </property>
    <property name="password" type="string">
      <column  name="password" length="30" not-null="true"/>
    </property>
  </class>
</hibernate-mapping>

 

 

posted on 2014-12-17 15:40  aicpcode  阅读(222)  评论(0编辑  收藏  举报

导航