Struts2+Hibernate简单整合

  1. 框架整合,只是将不同的框架负责不同的内容。如struts2依旧是负责控制器Controller,而Hibernate及Mybitas负责的是DAO持久层对数据进行操作。
  2. 步骤
    • 编写DAO

O 实体并添加注解
R类
注册表
API测试


  • Service(Tx事务)

  • Struts2
    包括Action:
    1.Action 的类
    2.成员变量收集数据
    3.业务对象调用
    4.页面跳转
    Struts.xml文件的配置.


新建一个s2h项目进行Struts2和Hibernate的简单整合实例.
1. 导入项目所必须的jar包如下图:
这里写图片描述
其中包含了Struts2以及Hibernate的基础jar包和MySQL的jar,如果不导入mysql的jar则无法与数据库进行数据交换.
2. 在src下新建entity包建User类,设定属性并添加注解代码如下

package entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**
 * import javax.persistence.Entity;导入的这个包是持久化作用
 * 这里使用注解将类实现持久化
 *@author xpengfei
 *@creat  10:39:30 AM   Aug 24, 2017
 */

@Entity
@Table(name="t_user")
public class User {
    @Id
    @GenericGenerator(name="user_pk",strategy="increment")
    @GeneratedValue(generator="user_pk")
    private Integer id;
    private String name;
    private String password;


    public User(Integer id, String name, String password) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
    }
    public User() {

    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password
                + "]";
    }


}
  1. 导入hibernate.cfg.xml进行相关配置并进行User类的注册
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory >
        <property name="connection.username">root</property>
        <property name="connection.password">mysql</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///s2h?useUnicode=true&amp;characterEncoding=UTF-8</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

        <!-- 这里是 当调用时hibernate将session绑定到当前线程,
        事务结束后hibernate将session从当前线程中释放并且关闭session-->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- 类的注册 -->
        <mapping class="entity.User"/>

    </session-factory>
</hibernate-configuration>
  1. 建立init.sql文件编写建表语句
,create table t_user(
    id integer primary key,
    name varchar(12),
    password varchar(12)
);
  1. 创建util包,新建HibernateUtil.Java作为SessionFactory获取session的工具类
package util;

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

/**
 *@author xpengfei
 *@creat  10:38:37 AM   Aug 24, 2017
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;


    static{
        Configuration cfg=new Configuration();
        cfg.configure();

        sessionFactory=cfg.buildSessionFactory();
    }
    public static Session openSession(){

        return sessionFactory.openSession();
    }
    public static Session getCurrentSession(){
        System.out.println("获取session");
        return sessionFactory.getCurrentSession();
    }
}
  1. 新建dao包,创建UserDAO接口类以及UserDAOImpl接口实现类
package dao;

import entity.User;

/**
 *@author xpengfei
 *@creat  10:57:46 AM   Aug 24, 2017
 */
public interface UserDAO {
    public void save(User user);
}
package dao;

import org.hibernate.Session;

import util.HibernateUtil;

import entity.User;

/**
 *@author xpengfei
 *@creat  10:58:44 AM   Aug 24, 2017
 */
public class UserDAOImpl implements UserDAO{

    @Override
    public void save(User user) {
        //通过工具类获取session
        Session session=HibernateUtil.getCurrentSession();
        session.save(user);
    }

}
  1. 新建service包,创建UserService接口类以及UserServiceImpl实现类
package service;

import entity.User;

/**
 *@author xpengfei
 *@creat  11:15:57 AM   Aug 24, 2017
 */
public interface UserService {
    public void register(User user);
}
package service;

import org.hibernate.Transaction;

import util.HibernateUtil;
import dao.UserDAO;
import dao.UserDAOImpl;
import entity.User;

/**
 *@author xpengfei
 *@creat  11:16:57 AM   Aug 24, 2017
 */
public class UserServiceImpl implements UserService{

    private UserDAO userDAO=(UserDAO) new UserDAOImpl();
    @Override
    public void register(User user) {
        Transaction tx=null;
        try {
            //开启事务
            tx=HibernateUtil.getCurrentSession().getTransaction();
            tx.begin();
            userDAO.save(user);
            System.out.println("UserServiceImpl"+user);
            tx.commit();//提交事务
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            tx.rollback();
        }


    }

}
  1. 编写Action,新建action包,创建UserAction类
package action;

import service.UserService;
import service.UserServiceImpl;

import com.opensymphony.xwork2.Action;

import entity.User;

/**
 *@author xpengfei
 *@creat  11:22:03 AM   Aug 24, 2017
 */
public class UserAction implements Action{

    private User user;
    private UserService us=(UserService) new UserServiceImpl();
    public User getUser() {
        return user;
    }

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

    @Override
    public String execute() throws Exception {

        us.register(user);
        return "success";
    }

}
  1. 新建struts.xml进行相关action的配置这里写图片描述
  2. web.xml中进行struts2的核心控制器的配置这里写图片描述
  3. 新建View目录并在其下创建reg.jsp以及result.jsp做简单的测试reg.jspresult.jsp
  4. 项目根级目录这里写图片描述这里写图片描述
  5. 运行项目效果如下:
    这里写图片描述
    注册成功后
    这里写图片描述
    数据库数据表中的数据:
    这里写图片描述
    数据存储成功;
    至此,struts2+Hibernate简单的注册整合完成.

 

posted @ 2017-08-24 15:45  竹芒  阅读(318)  评论(0编辑  收藏  举报