Hibernate学习总结

首先声明这是个坑爹的框架

属于ssh经典框架中的持久层框架,说白了就是管理数据库的。

下载地址:http://hibernate.org/orm/

这里写了版本5.2,下载下来的基本不怎么会用,因为文件结构变化太大,也可能没什么人用了。所以我下了3点多版的。

想方便使用Hibernate框架,还要下个Hibernate Tools,不下也行就是写配置文件方便点而已。

下载地址:http://hibernate.org/tools/

配置Tools只要把features,plugins两个文件夹copy到eclipse中就行,eclipse本身就有这两个文件夹,点合并。

想要在项目中用Hibernate,肯定要导jar包吧,教程坑爹的只告诉你导入hibernate3.jar这个包。

是的,导入之后运行就会告诉你还要导别的包。现在一次说总结清楚。

首先导入hibernate3.jar

然后导入required包,运行发现还要个jpa,就把jpa包导入,才能运行成功,它们都在lib下的。

 

写成一个Hibernate的Demo真的麻烦,有人教你在配置后用mapping这玩意么

运行需要几个东西:hibernate.cfg.xml,类名.cfg.xml,类

有了Tools这个东西,就不用担心了。

首先hibernate.cfg.xml放在src包下,类名.cfg.xml放在与类同包下。

hibernate.cfg.xml

<?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.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">账号</property>
        <property name="connection.password">密码</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/数据库名?useSSL=true</property>
        <property name="connection.characterEncoding">utf-8</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping resource="package2/persion.hbm.xml" />
    </session-factory>
</hibernate-configuration>

类名.cfg.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-7-20 15:57:35 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="package2.persion" table="PERSION">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
    </class>
</hibernate-mapping>

persion.java

public class persion {
    int id;
    String name;
    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;
    }
    
}

HibernateExecute.java

import java.util.Iterator;
import java.util.List;

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

public class HibernateExecute {

    public static void main(String[] args) {
        Configuration cfg=new Configuration().configure();
        SessionFactory ssf=cfg.buildSessionFactory();
        Session session=ssf.openSession();
        session.beginTransaction();
        String hql="FROM persion";
        Query q=session.createQuery(hql);
        List list=q.list();
        Iterator<persion> it=list.iterator();
        while(it.hasNext()){
            persion p=it.next();
            System.out.println(p.getId()+" "+p.getName());
        }
        
        if(session.isOpen())
            session.close();
    }

}

persion是这样一个简单的表

运行后无疑是正常的

 

写单机程序是非常无趣的,只不过它给定了一个范式。

struts2+hibernate3合体是这样写的

DAO层该干嘛干嘛,Action负责调用DAO层处理数据然后传输到页面。就这么简单。

按照惯例先定义一个接口:

import java.util.List;

public interface DataOperation {
    public boolean InsertIntoUser(user user);
    public boolean DeleteUser(user user);
    public List QueryAllUser();
    public void updateUser(user user);
    public List<user> SelectUser(user user);
}

然后接口实现类:

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.envers.RevisionTimestamp;

public class OperationImpl implements DataOperation{
    

    @Override
    public boolean InsertIntoUser(user user) {
        // TODO Auto-generated method stub
        boolean success=false;
        SessionInstance getsession=new SessionInstance();
        Session session=getsession.SessionInstance();
        session.beginTransaction();
        String hql="from user as user where user.username=:name";
        Query q=session.createQuery(hql);
        q.setString("name", user.getUsername());
        List<user> list=q.list();
        if(list.isEmpty())
        {
            session.save(user);
            session.getTransaction().commit();
            
            success=true;
        }
        session.close();
        return success;
    }

    @Override
    public boolean DeleteUser(user user) {
        System.out.println("删除执行");
        // TODO Auto-generated method stub
        boolean isDelete=false;
        SessionInstance getsession=new SessionInstance();
        Session session=getsession.SessionInstance();
        session.beginTransaction();
        String hql="from user as user where user.username=:name";        
        Query q=session.createQuery(hql);
        q.setString("name", user.getUsername());
        List<user> l=q.list();

        if(!l.isEmpty())
        {
            String del="delete user where username=:name";
            Query delete=session.createQuery(del);
            delete.setParameter("name", user.getUsername());
            delete.executeUpdate();
            session.getTransaction().commit();
            isDelete=true;
            System.out.println("删除成功:"+user.getUsername());
        }
        session.close();
        return isDelete;
    }

    @Override
    public List<user> QueryAllUser() {
        SessionInstance getsession=new SessionInstance();
        Session session=getsession.SessionInstance();
        Query q=session.createQuery("from user");
        List<user> list=q.list();
        session.close();
        return list;
    }

    @Override
    public void updateUser(user user) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public List<user> SelectUser(user user) {
        SessionInstance getsession=new SessionInstance();
        Session session=getsession.SessionInstance();
        session.beginTransaction();
        String hql="from user as user where user.username=:name and user.tel=:tel";
        Query q=session.createQuery(hql);
        q.setString("name", user.getUsername());
        q.setString("tel", user.getTel());
        List<user> l=q.list();
        System.out.println("空:"+l.isEmpty());
        session.close();
        return l;
    }

}

然后类似一个工具类

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

public class  SessionInstance {
    public Session SessionInstance(){
        Configuration cfg=new Configuration().configure();
        SessionFactory sessionFactory=cfg.buildSessionFactory();
        Session session=sessionFactory.openSession();
        return session;
        
    }
}

注意Session,Configuration这些都是hibernate包下的。

然后就是写几个页面了,配action啊之类的。

QueryAll和Update没写,一个模式就不写了。还没搞懂怎么从POJO的List传到前端,所以QueryAll直接写成JSP了。

<%@page import="org.hibernate.SessionFactory"%>
<%@page import="DAOLayer.user"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.hibernate.Query"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>遍历数据表</title>
</head>
<body>
    <%
        Configuration cfg=new Configuration().configure();
        SessionFactory sf=cfg.buildSessionFactory();
        Session ses=sf.openSession();
        ses.beginTransaction();
        String hql="FROM user";
        Query q=ses.createQuery(hql);
        List list=q.list();
        Iterator<user> it=list.iterator();
        while(it.hasNext()){
            user u=it.next();
            out.write("用户名:"+u.getUsername()+" 密码:"+u.getPassword()+" 电话号码:"+u.getTel());
            out.print("<br/>");
        }
        
        if(ses.isOpen())
            ses.close();
        
    %>
</body>
</html>

持久层对象user.java

public class user {
    private String username;
    private String password;
    private String tel;
    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 String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }

}

数据表也是个简单表。

 

值得注意的是,这个主键id根本不需要管它,自增的话不需要写进持久层对象,会有什么问题我就不懂了,至今还正常。

再贴几个Action

InsertActon.java

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import DAOLayer.OperationImpl;
import DAOLayer.user;

public class InsertAction extends ActionSupport implements ModelDriven<user>{
    private user user =new user();
    public user getUser() {
        return user;
    }

    public void setUser(user user) {
        this.user = user;
    }

    public String execute(){
        System.out.println(user.getUsername() + " " + user.getPassword() + " " + user.getTel());

        OperationImpl insert = new OperationImpl();
        boolean IsSuccess = insert.InsertIntoUser(user);
        if (IsSuccess) {
            ActionContext context = ActionContext.getContext();
            context.getSession().put("username", user.getUsername());
            context.getSession().put("telephone", user.getTel());
            return SUCCESS;
        }
        return "faliure";
        
    }

    @Override
    public user getModel() {

        return this.user;
    }

}

DeleteAction.java

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import DAOLayer.OperationImpl;
import DAOLayer.user;

public class DeleteAction extends ActionSupport implements ModelDriven<user>{
    
    private user user=new user();
    @Override
    public user getModel() {
        // TODO Auto-generated method stub
        return user;
    }
    
    public String execute(){
        OperationImpl delete=new OperationImpl();
        boolean b=delete.DeleteUser(user);
        if(b)
            return SUCCESS;
        return "faliure";
    } 

}

 

SelectAction.java

import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import DAOLayer.OperationImpl;
import DAOLayer.user;

public class SelectAction extends ActionSupport implements ModelDriven<user>{
    private user user=new user();
    
    public String execute(){
        OperationImpl select=new OperationImpl();
        List<user> list=select.SelectUser(user);
        if (!list.isEmpty()) {
            for (user u : list)
                System.out.println(u.getUsername() + " " + u.getPassword() + " " + u.getTel());
            ActionContext context = ActionContext.getContext();
            context.getSession().put("username_result", list.get(0).getUsername());
            context.getSession().put("password_result", list.get(0).getPassword());
            context.getSession().put("tel_result", list.get(0).getTel());
        }
        return SUCCESS;
    }

    @Override
    public user getModel() {
        // TODO Auto-generated method stub
        return user;
    }
}

最后贴个搜索结果处理,感觉这些api还不够方便,而且Action传值只能使用s标签库,每个jsp都会被服务器解析,会影响服务器效率。今后尝试使用AJAX技术吧,还没学会。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>查询结果</title>
</head>
<body>
    <%
        String username="";
        if(!(session.getAttribute("username_result")==null))
            username=session.getAttribute("username_result").toString();
        String passwd="";
        if(!(session.getAttribute("password_result")==null))
             passwd=session.getAttribute("password_result").toString();
        String tel="";
        if(!(session.getAttribute("tel_result")==null))
            tel=session.getAttribute("tel_result").toString();
        System.out.println("用户名:"+username);
        if(username.equals(""))
        {
            out.print("没有此用户");
            out.print("<br/>");
        }
        else
        {
            out.print("用户名:"+username);
            out.print("<br/>");
            out.print("密码:"+passwd);
            out.print("<br/>");
            out.print("电话:"+tel);
            out.print("<br/>");
        }
        
    %>
</body>
</html>

 

运行还算顺利。

posted @ 2016-07-21 21:42  天目山电鳗  阅读(1457)  评论(0编辑  收藏  举报