SSH框架学习(五、在struts和spring基础上加入hibernate)

Hibernate有很机械的pojo类和hbm文件要写,这部分用myeclipse来做,能省不少事情,终于又感觉到myeclipse的好处了。


1、先在mysql里面建个表

CREATE TABLE `t_user` (
  `pk_user_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `login_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `password` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`pk_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、让myeclipse连接到数据库,还会帮我们自动生成hibernate的配置文件,和一个sessionFactory类。


3、用myeclipse生成实体类和映射配置文件,在myeclipse的db browser里面,打开数据库,选中表。

最后会生成这样一堆文件

整理一下,我是这么放的


4、把myeclipse添加的lib引用去掉,换成hibernate4。

就是这两个hibernate 3.3的,去掉。

hibernate最新版是4.1.8,下载地址http://sourceforge.net/projects/hibernate/files/hibernate4/

解压开后,在lib目录下有个叫required的目录,下面放的是最基本的包,这个我喜欢,比struts和spring做的好。

引入这些包就好了

此外还需要mysql的连接包,最新版本5.1.22,下载地址:http://www.mysql.com/downloads/connector/j/


5、现在开始来修改,从web页面开始


在网站根目录下,增加一个user目录,下面添加一个add.jsp文件。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'add.jsp' starting page</title>  
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
  </head>
  <body>
    <form name="form1" method="post" action="user!add.action">
      <p>
        <label for="loginname">loginname</label>
        <input type="text" name="loginname">
      </p>
      <p>
        <label for="email">email</label>
        <input type="text" name="email">
      </p>
      <p>
        <label for="password">password</label>
        <input type="text" name="password">
      </p>
      <p>
        <input type="submit" name="submit" value="提交">
      </p>
    </form>
  This is my JSP page. <br>
  </body>
</html>


这个页面,将内容提交到了UserAction类的add方法,现在来修改UserAction类。

UserAction类里面要添加add方法,和接收页面信息的属性及方法。

package demo.myssh.action;

import com.opensymphony.xwork2.ActionSupport;
import demo.myssh.business.UserService;
import demo.myssh.model.User;

@SuppressWarnings("serial")
public class UserAction extends ActionSupport {

	@Override
	public String execute() throws Exception {

		this.addActionMessage("UserAction working");
		// this.addActionMessage("hello world.");
		this.addActionMessage(userService.doing());// 修改下,确认注入成功。

		return ActionSupport.SUCCESS;
	}

	// 注入用属性
	private UserService userService;

	// 注入用的方法
	public void setUserService(UserService userService) {
		this.userService = userService;
	}


	public String add() throws Exception {
		userService.save(new User(loginname, email, password));
		return ActionSupport.SUCCESS;
	}

	private String loginname;
	private String email;
	private String password;

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

这里面,用到了UserService类里面的save方法,继续修改UserService。

package demo.myssh.business;

import demo.myssh.dao.UserDAO;
import demo.myssh.model.User;

public class UserService {

	public String doing() {
		return "UserService working";
	}

	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void save(User user) {
		userDAO.save(user);
	}
}

UserDAO这个类不需要多少修改,只需要把里面日志有关的地方去掉就可以了。因为,我没有引入那个类。大家都喜欢用log4j,打算之后加入log4j。

package demo.myssh.dao;

import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import demo.myssh.model.User;

public class UserDAO extends BaseHibernateDAO {

    // property constants
    public static final String LOGIN_NAME = "loginName";
    public static final String EMAIL = "email";
    public static final String PASSWORD = "password";

    public void save(User transientInstance) {

        try {
            getSession().save(transientInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public void delete(User persistentInstance) {

        try {
            getSession().delete(persistentInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public User findById(java.lang.Long id) {

        try {
            User instance = (User) getSession().get("User", id);
            return instance;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public List findByExample(User instance) {

        try {
            List results = getSession().createCriteria("User")
                    .add(Example.create(instance)).list();

            return results;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {

        try {
            String queryString = "from User as model where model."
                    + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public List findByLoginName(Object loginName) {
        return findByProperty(LOGIN_NAME, loginName);
    }

    public List findByEmail(Object email) {
        return findByProperty(EMAIL, email);
    }

    public List findByPassword(Object password) {
        return findByProperty(PASSWORD, password);
    }

    public List findAll() {

        try {
            String queryString = "from User";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public User merge(User detachedInstance) {

        try {
            User result = (User) getSession().merge(detachedInstance);

            return result;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public void attachDirty(User instance) {

        try {
            getSession().saveOrUpdate(instance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public void attachClean(User instance) {

        try {
            getSession().lock(instance, LockMode.NONE);

        } catch (RuntimeException re) {

            throw re;
        }
    }
}

BaseHibernateDAO 不用改,沿用

package demo.myssh.dao;

import org.hibernate.Session;


public class BaseHibernateDAO implements IBaseHibernateDAO {
	
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}
	
}

IBaseHibernateDAO 不用改,沿用

package demo.myssh.dao;

import org.hibernate.Session;

public interface IBaseHibernateDAO {
	public Session getSession();
}

HibernateSessionFactory这个类要修改,因为hibernate 4 创建session的方法变了。

package demo.myssh.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionFactory {

	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;
	private static ServiceRegistry serviceRegistry;

	static {
		try {
			//hibernate 3 的方法
			// configuration.configure(configFile);
			// sessionFactory = configuration.buildSessionFactory();

			//hibernate 4 的方法
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.configure().getProperties())
					.buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (HibernateException e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	private HibernateSessionFactory() {
	}

	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;
	}


	public static void rebuildSessionFactory() {
		try {
			// configuration.configure(configFile);
			// sessionFactory = configuration.buildSessionFactory();

			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.configure().getProperties())
					.buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (HibernateException e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}


	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

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


	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}


	public static Configuration getConfiguration() {
		return configuration;
	}

}

User实体类不用改,不过还是贴出来吧。

package demo.myssh.model;

public class User implements java.io.Serializable {

	private static final long serialVersionUID = -8290754809696899650L;
	private Long userID;
	private String loginName;
	private String email;
	private String password;


	/** default constructor */
	public User() {
	}

	/** full constructor */
	public User(String loginName, String email, String password) {
		this.loginName = loginName;
		this.email = email;
		this.password = password;
	}

	// Property accessors

	public Long getUserID() {
		return this.userID;
	}

	public void setUserID(Long userID) {
		this.userID = userID;
	}

	public String getLoginName() {
		return this.loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

还有映射文件,记得添加下package,让hibernate能找到实体类

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC  
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping  package="demo.myssh.model">
    <class name="User" table="t_user" catalog="myssh">
        <id name="userID" type="java.lang.Long">
            <column name="pk_user_id" />
            <generator class="identity"></generator>
        </id>
        <property name="loginName" type="java.lang.String">
            <column name="login_name"  length="45"/>
        </property>
        <property name="email" type="java.lang.String">
            <column name="email"  length="45"/>
        </property>
        <property name="password" type="java.lang.String">
            <column name="password"  length="45"/>
        </property>
    </class>
</hibernate-mapping>

然后是hibernate的配置文件,

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!-- properties -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

		<property name="connection.url">jdbc:mysql://localhost:3306/myssh</property>
		<property name="connection.username">root</property>
		<property name="connection.password"></property>

		<property name="connection.autocommit">true</property>

		<!-- mapping files -->
		<mapping resource="demo/myssh/model/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>
这里注意,要添加autocommit属性,因为是用的myeclipse提供的sessionFactory。mapping路径也不要忘了。


最后,修改spring的配置文件applicationContext.xml,提供注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	 http://www.springframework.org/schema/util
	 http://www.springframework.org/schema/util/spring-util-3.0.xsd">


	<bean id="userAction" class="demo.myssh.action.UserAction">
		<property name="userService" ref="userService" />
	</bean>

	<bean id="userService" class="demo.myssh.business.UserService">
		<property name="userDAO" ref="userDAO"></property>
	</bean>

	<bean id="userDAO" class="demo.myssh.dao.UserDAO">
	</bean>
	
</beans>

运行访问:http://localhost:8080/user/add.jsp

提交以后,又转回index.jsp,查看数据库

大功告成,最基本简单的ssh框架搭建终于完成。


程序结构再贴下



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值