一、
用户管理系统,使用Hibernate向数据库表中添加一个用户,将所有的用户信息查出来并显示在页面上。
所需工具:MyEclipse、MySql数据库
二、
1.数据库建表
新建一个数据库javaweb,并在该数据库下创建一个表USER并存入几条数据
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`realname` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '张三', '1111', '张三', '18', '男', '山东省');
INSERT INTO `user` VALUES ('2', 'anna', '2017', 'anna', '19', '女', '美国');
2.环境配置
①直接向lib下导入所需的jar包②用myeclipse自带的jar包
在这里我使用了第二种方法:
配置Hibernate:在项目上点击右键-->MyEclipse-->Add Hibernate Capabilities...默认到最后一步配置MySql.配置好Hibernate,会自动生成hibernate.cfg.xml和HibernateSessionFactory文件,在src下新建common包将HibernateSessionFactory文件放到里面。
配置Struts2:在项目上点击右键-->MyEclipse-->Add Struts Capabilities..-->选择Struts2最高版本,URL Pattern选择/*-->Finish
3.将mysql驱动jar包放到lib文件夹下
4.实体类User(对应数据表的USER)
在src目录下新建entity包,并创建Hibernate的POJO类User(普通的Java类作为持久化对象)
public class User {
// 用户编号.
private int id;
// 用户名.
private String username;
// 密码.
private String password;
// 真实姓名.
private String realname;
// 年龄.
private int age;
// 性别.
private String sex;
// 地址.
private String address;
//属性的getter和setter方法省略。。。
}
5.编写User类的Hibernate映射文件,将对象与数据库中的表建立联系
Hibernate映射文件是要告诉Hibernate持久化类和数据库表的映射信息。
在entity中创建User.hbm.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 2017-5-9 16:12:22 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<!-- class中name:实体类名称, table:数据库表名, catalog:数据库名称. -->
<class name="entity.User" table="USER" catalog="javaweb">
<id name="id" type="int">
<column name="ID" />
<generator class="native" /> <!-- 设置id为主键,自增. -->
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" />
</property>
<property name="realname" type="java.lang.String">
<column name="REALNAME" />
</property>
<property name="age" type="int">
<column name="AGE" />
</property>
<property name="sex" type="java.lang.String">
<column name="SEX" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
</class>
</hibernate-mapping>
6.编写Hibernate配置文件
Hibernate配置文件是告诉Hibernate连接的数据库的相关信息,数据库配置内容定义在hibernate.cfg.xml中。
hibernate.cfg.xml<?xml version="1.0" encoding="UTF-8"?>
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javaweb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置映射文件. -->
<mapping resource="entity/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
7.HibernateSessionFactory类可以由MyEclipse自动生成
在该类中读取hibernae.cfg.xml配置文件。
代码如下
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
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;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
8.编写数据库操作Dao类
在src目录下新建一个包dao,创建UserDao类
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import com.zrx.common.HibernateSessionFactory;
import com.zrx.entity.User;
public class UserDao {
//保存用户.
public int saveUser(User user) {
int num = 0;
Session session = null;
//由于Hibernate版本的差异,不能直接写Transaction transaction = null;要指定为org.hibernate.Transaction.
org.hibernate.Transaction transaction = null;
try {
session = HibernateSessionFactory.getSession();//获取session对象.
transaction = session.beginTransaction();//开启事务.
num = Integer.parseInt(session.save(user).toString());//保存数据.
transaction.commit();//提交事务.
} catch (Exception e) {
num = 0;
e.printStackTrace();
} finally {
HibernateSessionFactory.closeSession();//关闭session.
}
return num;
}
//查询全部的用户信息.
@SuppressWarnings("unchecked")
public List<User> getUsers() {
List<User> users = new ArrayList<User>();
try {
Session session = HibernateSessionFactory.getSession();//获得session对象.
//创建查询语句,字符串中的User必须与entity中的User实体类名称相同.
users = session.createQuery("from User order by id").list();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateSessionFactory.closeSession();
}
return users;
}
}
9.业务控制Action类
在src下新建包action,在包下创建类UserAction
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.zrx.dao.UserDao;
import com.zrx.entity.User;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private User user;
UserDao userDao = new UserDao();
private List<User> userList;
//保存用户.
public String execute() {
userDao.saveUser(user);
return SUCCESS;
}
//获取用户.
public String getUsers() {
userList = userDao.getUsers();
return "list";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
return userList;
}
}
10.struts.xml中配置Action
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="user" namespace="/" extends="struts-default">
<action name="user" class="action.UserAction">
<result type="redirectAction">
<param name="namespace">/</param>
<param name="actionName">user</param>
<param name="method">getUsers</param>
</result>
<result name="list">/index.jsp</result>
</action>
</package>
</struts>
11.用户添加界面register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>
<s:form action="user" namespace="/" method="post">
<s:textfield name="user.username" label="用户名" size="20"></s:textfield>
<s:password name="user.password" label="密码" size="20"></s:password>
<s:textfield name="user.realname" label="真实姓名" size="20"></s:textfield>
<s:textfield name="user.age" label="年龄" size="20"></s:textfield>
<s:radio list="#{'男':'男','女':'女' }" label="性别" value="'男'" name="user.sex"></s:radio>
<s:textfield name="user.address" label="通讯地址" size="20"></s:textfield>
<s:submit value="用户添加"></s:submit>
</s:form>
</body>
</html>
12.用户显示界面index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>
<table>
<tr bgcolor="#E7E7E7">
<td height="24" colspan="6"> 用户列表 </td>
</tr>
<tr align="center" bgcolor="#FAFAF1" height="22">
<td width="28%">用户名</td>
<td width="10%">密码</td>
<td width="20%">真实姓名</td>
<td width="8%">年龄</td>
<td width="6%">性别</td>
<td width="8%">通讯地址</td>
</tr>
<s:iterator value="userList" var="user">
<tr>
<td><s:property value="#user.username" /></td>
<td><s:property value="#user.password" /></td>
<td><s:property value="#user.realname" /></td>
<td><s:property value="#user.age" /></td>
<td><s:property value="#user.sex" /></td>
<td><s:property value="#user.address" /></td>
</tr>
</s:iterator>
</table>
</body>
</html>