实体类
班级类
public class Classes {
private int cid;
private String cname;
private String copendate;
//构造器和javaBean方法省略
}
学生类
public class Students {
private int sid;
private String sname;
private String ssex;
private Date sdate;
private int cid;
//关联的多对一的类
private Classes classes;
//构造器和javaBean方法省略
}
分页类
public class PageBean {
private int page;
private int pageSize;
private int totalRecord;
private int totalPage;
private List<Students> slist=new ArrayList<>();
//构造器和javaBean方法省略
}
hbm.xml配置文件
Classes配置文件
<?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-8-6 14:54:56 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.mingde.po.Classes" table="CLASSES">
<id name="cid" type="int">
<column name="CID" />
<generator class="assigned" />
</id>
<property name="cname" type="java.lang.String">
<column name="CNAME" />
</property>
<property name="copendate" type="java.lang.String">
<column name="COPENDATE" />
</property>
</class>
</hibernate-mapping>
Students配置文件
<?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-8-6 14:54:56 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.mingde.po.Students" table="STUDENTS">
<!-- 生成主键 -->
<id name="sid" type="int">
<column name="SID" />
<generator class="sequence">
<param name="sequence">sequ06</param>
</generator>
</id>
<!-- 映射其它字段 -->
<property name="sname" type="java.lang.String">
<column name="SNAME" />
</property>
<property name="ssex" type="java.lang.String">
<column name="SSEX" />
</property>
<property name="sdate" type="java.sql.Date">
<column name="SDATE" />
</property>
<!--
//映射多对一
column:代表映射外键列
lazy:false代表加载当前的students对象时会立即加载其关联对象,需要注意的是:
在四种关联关系中,除了一对一是立即加载外,其余三种都是延迟加载。
-->
<!-- 多对一 -->
<many-to-one name="classes" class="com.mingde.po.Classes" fetch="join" lazy="false" >
<column name="CID" />
</many-to-one>
</class>
</hibernate-mapping>
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">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="format_sql"></property>
<property name="show_sql"></property>
<mapping resource="com/mingde/po/Classes.hbm.xml"/>
<mapping resource="com/mingde/po/Students.hbm.xml"/>
</session-factory>
</hibernate-configuration>
utils包的HibernateSessionFactory.java类
package com.mingde.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateSessionFactory {
//构造session工厂
private static SessionFactory sessionFactory;
//构造文件配置
private static Configuration config=new Configuration();
//构造本地线程来存储session,以来判断session有值
private static ThreadLocal<Session> threadLocal=new ThreadLocal<>();
static{
//加载配置
config.configure();
//创建注册服务
ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建工厂
sessionFactory =config.buildSessionFactory(serviceRegistry);
}
//过去getSession
public static Session getSession(){
Session session=threadLocal.get();
if(session==null || !session.isOpen()){
if(sessionFactory==null){
rebuildSessionFactory();
}
}
session=(sessionFactory!=null)?sessionFactory.openSession():null;
threadLocal.set(session);
return session;
}
private static void rebuildSessionFactory() {
//读取配置
config.configure();
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory=config.buildSessionFactory(serviceRegistry);
}
public static void closeSessionFactory(){
Session session = threadLocal.get();
threadLocal.set(null);
if(session!=null)session.close();
}
}
Struts.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<constant name="struts.devMode" value="true"></constant>
<package name="struts" extends="struts-default">
<action name="*_*" class="com.mingde.action.StudentsAction" method="{2}">
<result name="{2}">/WEB-INF/{1}/{2}.jsp</result>
<result name="to_list" type="redirect">{1}_list</result>
</action>
</package>
</struts>
Action类
package com.mingde.action;
import java.util.ArrayList;
import java.util.List;
import com.mingde.dao.IBaseDao;
import com.mingde.dao.impl.BaseDaoImpl;
import com.mingde.po.Classes;
import com.mingde.po.PageBean;
import com.mingde.po.Students;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class StudentsAction extends ActionSupport{
private IBaseDao bd=new BaseDaoImpl();
private List<Students> slist=new ArrayList<>();
private List<Classes> clist=new ArrayList<>();
private Students st=new Students();
private PageBean pb=new PageBean();
public String list() throws Exception {
//模糊查询的班级下拉列表
clist=bd.finAll("from Classes");
//构造hql语句
String hql="from Students where 1=1";
if(st.getSname()!=null && !"".equals(st.getSname()))hql+=" and sname like'%"+st.getSname()+"%' ";
if(st.getClasses()!=null && st.getClasses().getCid()!=0)hql+=" and classes.cid="+st.getClasses().getCid();
//当前页数
if(pb.getPage()==0)pb.setPage(1);
//每页的显示记录
if(pb.getPageSize()==0)pb.setPageSize(5);
//分页是所有记录
pb=bd.SeeAll(hql,pb.getPage(),pb.getPageSize());
return "list";
}
public String toAdd() throws Exception {
clist=bd.finAll("from Classes");
return "toAdd";
}
public String toUpdate() throws Exception {
clist=bd.finAll("from Classes");
st=(Students)bd.findOne(st.getClass(),st.getSid());
return "toUpdate";
}
public String add() throws Exception {
bd.add(st);
return "to_list";
}
public String update() throws Exception {
bd.update(st);
return "to_list";
}
public String del() throws Exception {
bd.del(st);
return "to_list";
}
public List<Students> getSlist() {
return slist;
}
public PageBean getPb() {
return pb;
}
public void setPb(PageBean pb) {
this.pb = pb;
}
public void setSlist(List<Students> slist) {
this.slist = slist;
}
public List<Classes> getClist() {
return clist;
}
public void setClist(List<Classes> clist) {
this.clist = clist;
}
public Students getSt() {
return st;
}
public void setSt(Students st) {
this.st = st;
}
}
Dao层
package com.mingde.dao.impl;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.mingde.dao.IBaseDao;
import com.mingde.po.PageBean;
import com.mingde.po.Students;
import com.mingde.utils.HibernateSessionFactory;
public class BaseDaoImpl implements IBaseDao {
@Override
public List finAll(String hql) {
List list=null;
//获取session
Session session=HibernateSessionFactory.getSession();
//创建事务
Transaction tx=null;
try{
//开启事务
tx=session.beginTransaction();
//执行命令
list=session.createQuery(hql).list();
//提交事务
tx.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
tx.rollback();
}finally{
//关闭事务
HibernateSessionFactory.closeSessionFactory();
}
return list;
}
@Override
public void add(Students st) {
//获取session
Session session=HibernateSessionFactory.getSession();
//创建事务
Transaction tx=null;
try{
//开启事务
tx=session.beginTransaction();
//执行命令
session.save(st);
//提交事务
tx.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
tx.rollback();
}finally{
//关闭事务
HibernateSessionFactory.closeSessionFactory();
}
}
@Override
public Students findOne(Class<?> class1, int sid) {
Students st=null;
//获取session
Session session=HibernateSessionFactory.getSession();
//创建事务
Transaction tx=null;
try{
//开启事务
tx=session.beginTransaction();
//执行命令
st=(Students) session.get(class1, sid);
//提交事务
tx.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
tx.rollback();
}finally{
//关闭事务
HibernateSessionFactory.closeSessionFactory();
}
return st;
}
@Override
public void update(Students st) {
//获取session
Session session=HibernateSessionFactory.getSession();
//创建事务
Transaction tx=null;
try{
//开启事务
tx=session.beginTransaction();
//执行命令
session.update(st);
//提交事务
tx.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
tx.rollback();
}finally{
//关闭事务
HibernateSessionFactory.closeSessionFactory();
}
}
@Override
public void del(Students st) {
//获取session
Session session=HibernateSessionFactory.getSession();
//创建事务
Transaction tx=null;
try{
//开启事务
tx=session.beginTransaction();
//执行命令
session.delete(st);
//提交事务
tx.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
tx.rollback();
}finally{
//关闭事务
HibernateSessionFactory.closeSessionFactory();
}
}
@Override
public PageBean SeeAll(String hql, int page, int pageSize) {
int totalRecord = 0;
int totalPage= 0;
List<Students> slist = null;
//获取session
Session session=HibernateSessionFactory.getSession();
//创建事务
Transaction tx=null;
try{
//开启事务
tx=session.beginTransaction();
//执行命令
Query createQuery = session.createQuery(hql);
//获取数据中有几条数据
totalRecord=createQuery.list().size();
//获取该数据按pageSize来分页可分成几页
totalPage=(int)Math.ceil((double)totalRecord/pageSize);
//从数据中第几行开始取
createQuery.setFirstResult((page-1)*pageSize);
//一次取几条数据
createQuery.setMaxResults(pageSize);
slist=createQuery.list();
//提交事务
tx.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
tx.rollback();
}finally{
//关闭事务
HibernateSessionFactory.closeSessionFactory();
}
return new PageBean(page, pageSize, totalRecord, totalPage, slist);
}
}
JSP页面
list.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>Insert title here</title>
</head>
<script>
function $(v){
return document.getElementById(v);
}
//点击上下页和首页未页时进行跳转
function fun(v){
$('page').value=v;
$('frm').submit();
}
//修改没有显示记录时进行跳转
function fun2(v){
$('page').value=1;
$("pb.pageSize").value=v;
$('frm').submit();
}
</script>
<body>
<h2>列表</h2>
<table width=800 align="center" rules="rows">
<tr>
<td colspan=6>
<s:form action="students_list" theme="simple" id="frm" οnsubmit="fun(1)">
<s:hidden name="pb.page" id="page" />
<s:hidden name="pb.pageSize" id="pb.pageSize" />
<s:a href="students_toAdd">添加</s:a>
学生姓名:<s:textfield name="st.sname" id="sname" ></s:textfield>
班级<s:select name="st.classes.cid" id='cid' list="clist" listKey="cid" listValue="cname" headerKey="0" headerValue="全部班级" ></s:select>
<s:submit value="查询"></s:submit>
</s:form>
</td>
</tr>
<tr>
<th>学生编号</th><th>学生姓名</th><th>学生性别</th><th>学生生日</th><th>所在班级</th><th>操作</th>
</tr>
<s:iterator value="pb.slist">
<tr align="center">
<td><s:property value="sid"/></td>
<td><s:property value="sname"/></td>
<td><s:property value="ssex"/></td>
<td><s:date name="sdate" format="yyyy-MM-dd" /></td>
<td><s:property value="classes.cname"/></td>
<td>
<s:a href="students_toUpdate?st.sid=%{sid}">修改</s:a>
<s:a href="students_del?st.sid=%{sid}" οnclick="return confirm('确定删除?')">删除</s:a>
</td>
</tr>
</s:iterator>
<tr>
<td colspan=6 >
<s:if test="%{pb.page==1 && pb.totalPage>pb.page }">
<a href="javascript:void(0)" οnclick="fun(${pb.page+1})">下一页</a>
<a href="javascript:void(0)" οnclick="fun(${pb.totalPage})">尾页</a>
</s:if>
<s:if test="%{pb.page>1 && pb.page<pb.totalPage }">
<a href="javascript:void(0)" οnclick="fun(1)">首页</a>
<a href="javascript:void(0)" οnclick="fun(${pb.page-1})">上一页</a>
<a href="javascript:void(0)" οnclick="fun(${pb.page+1})">下一页</a>
<a href="javascript:void(0)" οnclick="fun(${pb.totalPage})">尾页</a>
</s:if>
<s:if test="%{pb.page>1 && pb.page==pb.totalPage }">
<a href="javascript:void(0)" οnclick="fun(1)">首页</a>
<a href="javascript:void(0)" οnclick="fun(${pb.page-1})">上一页</a>
</s:if>
<s:if test="%{pb.page==1 && pb.totalPage==1}">仅有此页</s:if>
<s:if test="%{pb.totalPage==0 }">暂无此信息</s:if>
<s:if test="%{pb.totalPage!=0 }">
第<span style="color:red;font-weight:bold">${pb.page }</span>页 / 共<span style="color:red;font-weight:bold">${pb.totalPage }</span>页
每页显示<s:textfield name="pb.pageSize" size="3" theme="simple" style="font-weight:bold;" οnblur="fun2(this.value)" />条记录
</s:if>
</td>
</tr>
</table>
</body>
</html>
toAdd页面
<%@ 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>Insert title here</title>
</head>
<body>
<h2>添加</h2>
<s:form action="students_add">
<s:textfield name="st.sname" label="姓名:"></s:textfield>
<s:radio name="st.ssex" label="性别" list="#{'M':'男','F':'女' }" value="'M'"></s:radio>
<s:textfield name="st.sdate" label="生日:"></s:textfield>
<s:select name="st.classes.cid" label="所在班级:" list="clist" listKey="cid" listValue="cname" ></s:select>
<s:submit value="添加"></s:submit>
</s:form>
</body>
</html>
toUpdate页面
<%@ 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>Insert title here</title>
</head>
<body>
<h2>修改</h2>
<s:form action="students_update">
<s:hidden name="st.sid"></s:hidden>
<s:textfield name="st.sname" label="姓名:"></s:textfield>
<s:radio name="st.ssex" label="性别" list="#{'M':'男','F':'女' }" ></s:radio>
<!-- 格式化文本框,使其输出的值显示为yyyy-MM-dd的格式 -->
<s:textfield name="st.sdate" label="生日:" >
<s:param name="value"><s:date format="yyyy-MM-dd" name="st.sdate" /></s:param>
</s:textfield>
<s:select name="st.classes.cid" label="所在班级:" list="clist" listKey="cid" listValue="cname" ></s:select>
<s:submit value="修改"></s:submit>
</s:form>
</body>
</html>