SSH框架学习

admin2025-10-16 03:00:549581

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

1、先在mysql里面建个表

[sql]

view plain

copy

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文件。

[html]

view plain

copy

<%@ 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+"/"; %> My JSP 'add.jsp' starting page

This is my JSP page.

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

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

[java]

view plain

copy

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。

[java]

view plain

copy

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。

[java]

view plain

copy

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 不用改,沿用

[java]

view plain

copy

package demo.myssh.dao; import org.hibernate.Session; public class BaseHibernateDAO implements IBaseHibernateDAO { public Session getSession() { return HibernateSessionFactory.getSession(); } }

IBaseHibernateDAO 不用改,沿用

[java]

view plain

copy

package demo.myssh.dao; import org.hibernate.Session; public interface IBaseHibernateDAO { public Session getSession(); }

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

[java]

view plain

copy

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 threadLocal = new ThreadLocal(); 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实体类不用改,不过还是贴出来吧。

[java]

view plain

copy

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能找到实体类

[html]

view plain

copy

然后是hibernate的配置文件,

[html]

view plain

copy

org.hibernate.dialect.MySQL5Dialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/myssh root true

这里注意,要添加autocommit属性,因为是用的myeclipse提供的sessionFactory。mapping路径也不要忘了。

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

[html]

view plain

copy

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

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

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

程序结构再贴下

搜索一下