struts2与Hibernate的整合,实现数据库后台数据更新

1.先把struts2,Hibernate,mysql架包加载到web project中来


jar包下载地址:
http://download.csdn.net/detail/hoho_12/9524001


2.User.java部分代码,一个简单的javabean和表字段一致

package com.hibernate.wxh;

public class User {
	private int id;
	private String username;
	private String userpwd;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpwd() {
		return userpwd;
	}
	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}	
}

3.User.hbm.xml代码





    
        
            
            
        
        
            
        
        
            
        
    


4.HibernateUtil.java工具类

package com.hibernate.wxh;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private static Configuration configuration = new Configuration();
	// 创建线程局部变量threadLocal,用来保存Hibernate的Session
	private static final ThreadLocal threadLocal = new ThreadLocal();

	// 使用静态代码块初始化Hibernate
	static {
		try {
			Configuration cfg = new Configuration().configure(); // 读取配置文件hibernate.cfg.xml
			sessionFactory = cfg.buildSessionFactory(); // 创建SessionFactory
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}

	// 获得SessionFactory实例
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	// 获得ThreadLocal 对象管理的Session实例.
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {

				rebuildSessionFactory();
			}
			// 通过SessionFactory对象创建Session对象
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			// 将新打开的Session实例保存到线程局部变量threadLocal中
			threadLocal.set(session);
		}
		return session;
	}

	// 关闭Session实例
	public static void closeSession() throws HibernateException {
		// 从线程局部变量threadLocal中获取之前存入的Session实例
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close();
		}
	}

	// 重建SessionFactory
	public static void rebuildSessionFactory() {
		try {
			configuration.configure("/hibernate.cfg.xml"); // 读取配置文件hibernate.cfg.xml
			sessionFactory = configuration.buildSessionFactory(); // 创建SessionFactory
		} catch (Exception e) {
			System.err.println("Error Creating SessionFactory ");
			e.printStackTrace();
		}
	}

	// 关闭缓存和连接池
	public static void shutdown() {
		getSessionFactory().close();
	}
}

5.UserDAO.java,包含两个方法,一个用来数据库里添加记录,一个用来取数据库里记录。

package com.hibernate.wxh;

import java.util.*; 

import org.hibernate.*;

public class UserDAO {
	public static ListgetUser(){
	List user=new ArrayList();
	Session session=HibernateUtil.getSession();
	user=session.createQuery("from User").list();
	HibernateUtil.closeSession();
	return user;
	}
	
	public static void addUser(User u){
		Session session=HibernateUtil.getSession();
		Transaction ts=session.beginTransaction();
		session.save(u);
		ts.commit();
		HibernateUtil.closeSession();
	}
}

6.hibernate.cfg.xml配置文件




    
        com.mysql.jdbc.Driver
        111
        jdbc:mysql://localhost/db_test
        root
        org.hibernate.dialect.MySQLDialect
        true
    	 true
    	  update
    	 
    


7. web.xml


        struts2
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    

    
        struts2
        /*
    

8. Struts.xml


 
 
 
 
 	
 		/index.jsp
 	 
 

9. UserAction

package com.struts2.wxh;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.hibernate.wxh.*;

public class UserAction extends ActionSupport implements ModelDriven{
	private User u=new User();

	
	public User getModel(){
		return u;
	}
	
	public User getU() {
		return u;
	}

	public void setU(User u) {
		this.u = u;
	}
	
	public String execute() throws Exception{
		UserDAO.addUser(u);
		return "success";
	}
	
}
10.index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*,com.hibernate.wxh.*" %>




Insert title here


用户名:

密码:

<% List user=UserDAO.getUser(); for(User u:user){ %> <%} %>
ID 用户名 密码
<%=u.getId() %> <%=u.getUsername() %> <%=u.getUserpwd() %>

项目完整源码下载地址:

http://download.csdn.net/detail/hoho_12/9524142


开发工具:

Eclipse + mysql+Tomcat8




你可能感兴趣的:(Hibernate,hibernate3小白入门)