ssh完成对oracle数据库的增删查改

本文介绍如何使用SSH(Struts2、Spring、Hibernate)三大框架整合进行书本管理项目的开发,涵盖从配置文件到控制层及显示层的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上篇博文已经完成利用Myeclipse 2014完成对ssh 三大框架的整合,这篇博文将通过一个书本管理的项目来熟悉框架对oracle数据库的操作,先上效果。


1.效果图

1.1 书本列表:


1.2 增加图书


1.3 修改图书


2. 文件配置

2.1 文件结构


2.2 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSH_Book</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationContext.xml</param-value>
  </context-param>
</web-app>

2.3 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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
	xmlns:tx="http://www.springframework.org/schema/tx">


	<!-- 定义数据源Bean,使用C3P0数据源实现,并注入数据源的必要信息 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close"
		p:driverClass="oracle.jdbc.driver.OracleDriver"
		p:jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl"
		p:user="scott"
		p:password="123456"
		p:maxPoolSize="40"
		p:minPoolSize="2"
		p:initialPoolSize="2"
		p:maxIdleTime="30"/>
	<!-- 定义Hibernate的SessionFactory,SessionFactory需要依赖数据源,注入dataSource -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
	p:dataSource-ref="dataSource">
		<!-- mappingResources用来列出全部映射文件 -->
		<property name="annotatedClasses">
			<list>
				<!-- 以下用来列出所有的PO类-->
				<value>org.crazyit.booksys.domain.Book</value>
			</list>
		</property>
		<!-- 定义Hibernate SessionFactory的属性 -->
		<property name="hibernateProperties">
			<props>
				<!-- 指定Hibernate的连接方言 -->
				<prop key="hibernate.dialect">
					org.hibernate.dialect.Oracle10gDialect</prop>
				<!--是否根据Hiberante映射创建数据表 -->
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>				
			</props>
		</property>
	</bean>
	<!-- 定义Service组件,并将DAO组件注入Service组件 -->	
	<bean id="bookService" class="org.crazyit.booksys.service.impl.BookServiceImpl"
		p:bookDao-ref="bookDao"/>
	<!-- 定义DAO组件,并将SessionFactory注入DAO组件 -->		
	<bean id="bookDao" class="org.crazyit.booksys.dao.impl.BookDaoHibernate4"
		p:sessionFactory-ref="sessionFactory"/>
	
	<!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->
	<!-- 该类是PlatformTransactionManager接口针对采用Hibernate的特定实现类 -->
	<!-- 配置HibernateTransactionManager需依赖注入SessionFactory -->
	<bean id="transactionManager" 
		class="org.springframework.orm.hibernate4.HibernateTransactionManager"
		p:sessionFactory-ref="sessionFactory"/>

	<!-- 配置事务增强处理Bean,指定事务管理器 -->
	<tx:advice id="txAdvice" 
		transaction-manager="transactionManager">
		<!-- 用于配置详细的事务定义 -->
		<tx:attributes>
			<!-- 所有以'get'开头的方法是read-only的 -->
			<tx:method name="get*" read-only="true"/>
			<!-- 其他方法使用默认的事务设置,指定超时时长为5秒 -->
			<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="5"/>
		</tx:attributes>
	</tx:advice>
	<!-- AOP配置的元素 -->
	<aop:config>
		<!-- 配置一个切入点 -->
		<aop:pointcut id="myPointcut" expression="bean(bookService)"/>
		<!-- 指定在myPointcut切入点应用txAdvice事务增强处理 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
	</aop:config>
	
</beans>

2.4 struts.xml

<?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>
	<constant name="struts.objectFactory" value="spring"/>
	<constant name="struts.i18n.encoding" value="UTF-8"/>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true"/>	
	<package name="lee" extends="struts-default">
		
		<action name="addBook" class="org.crazyit.booksys.action.BookAction"
			method="add">
			<!-- 添加图书成功,列出所有图书 -->
			<result name="success" type="redirectAction">listBooks</result>
			<!-- 添加图书失败,跳转到添加图书的表单页 -->
			<result name="error">/WEB-INF/content/bookForm.jsp</result>
		</action>
		<action name="editBook" class="org.crazyit.booksys.action.BookAction"
			method="edit">
			<result>/WEB-INF/content/editForm.jsp</result>
		</action>
		<action name="doEditBook" class="org.crazyit.booksys.action.BookAction"
			method="doEdit">
			<!-- 修改图书成功,列出所有图书 -->
			<result name="success" type="redirectAction">listBooks</result>
			<!-- 修改图书失败,跳转到添加图书的表单页 -->
			<result name="error">/WEB-INF/content/editForm.jsp</result>
		</action>
		<action name="listBooks" class="org.crazyit.booksys.action.BookAction"
			method="list">
			<result>/WEB-INF/content/listBooks.jsp</result>
		</action>
		<action name="deleteBook" class="org.crazyit.booksys.action.BookAction"
			method="delete">
			<result type="chain">listBooks</result>
		</action>		

		<!-- 让用户直接访问该应用时列出所有视图页面 -->
		<action name="*">
			<result>/WEB-INF/content/{1}.jsp</result>
		</action>
	</package>
</struts>    

3. 控制层文件

使用spring提倡是面向接口编程。下面只列出主要文件:

3.1 BookAction.java

package org.crazyit.booksys.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.crazyit.booksys.domain.Book;
import org.crazyit.booksys.service.BookService;

import com.opensymphony.xwork2.ActionSupport;
public class BookAction extends ActionSupport
{
	private BookService bookService;
	// 依赖注入BookService组件必须的setter方法。
	// 该方法的方法名要与BookService的配置id对应
	public void setBookService(BookService bookService)
	{
		this.bookService = bookService;
	}
	private Book book;
	private List<Book> books;
	private int id;
	public Book getBook()
	{
		return book;
	}
	public void setBook(Book book)
	{
		this.book = book;
	}
	
	public List<Book> getBooks()
	{
		return books;
	}
	public void setBooks(List<Book> books)
	{
		this.books = books;
	}
	
	public int getId()
	{
		return id;
	}
	public void setId(int id)
	{
		this.id = id;
	}
	// 处理添加图书的add()方法
	public String add()
	{
		// 调用业务逻辑组件的addBook()方法来处理用户请求		
		int result = bookService.addBook(book);
		if(result > 0)
		{
			addActionMessage("恭喜您,图书添加成功!");
			return SUCCESS;
		}
		addActionError("图书添加失败,请重新输入!");
		return ERROR;
	}
	public String list()
	{
		setBooks(bookService.getAllBooks());
		return SUCCESS;
	}
	public String delete()
	{
		bookService.deleteBook(id);
		return SUCCESS;
	}	
	public String edit()
	{
		setBook(bookService.getTheBooks(id));
		return SUCCESS;
	}	
	public String doEdit()
	{

		Map<String, Object> bookMap = new HashMap<String, Object>();
		bookMap.put("name", book.getName());
		bookMap.put("price", book.getPrice());	
		bookMap.put("author", book.getAuthor());	
		bookService.doEditBook(bookMap,id);
		return SUCCESS;
	}	
}

3.2 BookDaoHibernate4

package org.crazyit.booksys.dao.impl;

import java.util.List;

import org.crazyit.booksys.dao.BookDao;
import org.crazyit.booksys.domain.Book;
import org.crazyit.common.dao.impl.BaseDaoHibernate4;

public class BookDaoHibernate4 extends BaseDaoHibernate4<Book>
	implements BookDao
{
}

3.3 BookServiceImpl.java

package org.crazyit.booksys.service.impl;

import java.util.List;
import java.util.Map;

import org.crazyit.booksys.dao.BookDao;
import org.crazyit.booksys.domain.Book;
import org.crazyit.booksys.service.BookService;
public class BookServiceImpl implements BookService
{
	private BookDao bookDao;
	
	public void setBookDao(BookDao bookDao)
	{
		this.bookDao = bookDao;
	}

	@Override
	public int addBook(Book book)
	{
		return (Integer) bookDao.save(book);
	}

	@Override
	public List<Book> getAllBooks()
	{
		return bookDao.findAll(Book.class);
	}
	@Override
	public Book getTheBooks(int id)
	{
		return  bookDao.get(Book.class, id);
	}
	@Override
	public void deleteBook(int id)
	{
		bookDao.delete(Book.class, id);
	}
	@Override
	public void doEditBook(Map<String, Object> bookinfo,int id)
	{
		bookDao.updateData(Book.class, id, bookinfo);
	}
}

3.4 BaseDaoHibernate4.java
package org.crazyit.common.dao.impl;

import org.hibernate.*;

import java.util.List;
import java.util.Map;
import java.io.Serializable;
import java.util.Set;
import org.crazyit.common.dao.*;
public class BaseDaoHibernate4<T> implements BaseDao<T>
{
	// DAO组件进行持久化操作底层依赖的SessionFactory组件
	private SessionFactory sessionFactory;
	// 依赖注入SessionFactory所需的setter方法
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}
	public SessionFactory getSessionFactory()
	{
		return this.sessionFactory;
	}
	// 根据ID加载实体
	@SuppressWarnings("unchecked")
	public T get(Class<T> entityClazz , Serializable id)
	{
		return (T)getSessionFactory().getCurrentSession()
			.get(entityClazz , id);
	}
	// 保存实体
	public Serializable save(T entity)
	{
		return getSessionFactory().getCurrentSession()
			.save(entity);
	}
	// 更新实体
	public void update(String sql)
	{
		//getSessionFactory().getCurrentSession().saveOrUpdate(entity);
		getSessionFactory().getCurrentSession()
		.createQuery(sql).executeUpdate();
	}
	// 删除实体
	public void delete(T entity)
	{
		getSessionFactory().getCurrentSession().delete(entity);
	}
	// 根据ID删除实体
	public void delete(Class<T> entityClazz , Serializable id)
	{
		getSessionFactory().getCurrentSession()
			.createQuery("delete " + entityClazz.getSimpleName()
				+ " en where en.id = ?0")
			.setParameter("0" , id)
			.executeUpdate();
	}
	// 根据ID更新实体
	public void updateData(Class<T> entityClazz , Serializable id, Map<String, Object> bookinfo)
	{
		String sql = "set ";
		String mySql;
	    Set<String> get = bookinfo.keySet(); 
	    int len = bookinfo.size();
	    int i = 0;
	    System.out.println(len);
        for (String key:get) {
           // System.out.println(key+","+bookinfo.get(key));
            if(i<len-1) sql =  sql + "en." + key+" = '"+bookinfo.get(key)+"', ";
			else sql =  sql + "en." + key+" = '"+bookinfo.get(key)+"' ";
            i++;
        }
		mySql="update " + entityClazz.getSimpleName()+" en "+sql+" where en.id = ?0";
		System.out.println(mySql);
		getSessionFactory().getCurrentSession()
		.createQuery(mySql)
		.setParameter("0" , id)
		.executeUpdate();
	}
	// 获取所有实体
	public List<T> findAll(Class<T> entityClazz)
	{
		return find("select en from "
			+ entityClazz.getSimpleName() + " en");
	}
	// 获取实体总数
	
	public long findCount(Class<T> entityClazz)
	{
		List<?> l = find("select count(*) from "
			+ entityClazz.getSimpleName());
		// 返回查询得到的实体总数
		if (l != null && l.size() == 1 )
		{
			return (Long)l.get(0);
		}
		return 0;
	}

	// 根据HQL语句查询实体
	@SuppressWarnings("unchecked")
	protected List<T> find(String hql)
	{
		return (List<T>)getSessionFactory().getCurrentSession()
			.createQuery(hql)
			.list();
	}
	// 根据带占位符参数HQL语句查询实体
	@SuppressWarnings("unchecked")
	protected List<T> find(String hql , Object... params)
	{
		// 创建查询
		Query query = getSessionFactory().getCurrentSession()
			.createQuery(hql);
		// 为包含占位符的HQL语句设置参数
		for(int i = 0 , len = params.length ; i < len ; i++)
		{
			query.setParameter(i + "" , params[i]);
		}
		return (List<T>)query.list();
	}
	/**
	 * 使用hql 语句进行分页查询操作
	 * @param hql 需要查询的hql语句
	 * @param pageNo 查询第pageNo页的记录
	 * @param pageSize 每页需要显示的记录数
	 * @return 当前页的所有记录
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findByPage(String hql,
		 int pageNo, int pageSize)
	{
		// 创建查询
		return getSessionFactory().getCurrentSession()
			.createQuery(hql)
			// 执行分页
			.setFirstResult((pageNo - 1) * pageSize)
			.setMaxResults(pageSize)
			.list();
	}
	/**
	 * 使用hql 语句进行分页查询操作
	 * @param hql 需要查询的hql语句
	 * @param params 如果hql带占位符参数,params用于传入占位符参数
	 * @param pageNo 查询第pageNo页的记录
	 * @param pageSize 每页需要显示的记录数
	 * @return 当前页的所有记录
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findByPage(String hql , int pageNo, int pageSize
		, Object... params)
	{
		// 创建查询
		Query query = getSessionFactory().getCurrentSession()
			.createQuery(hql);
		// 为包含占位符的HQL语句设置参数
		for(int i = 0 , len = params.length ; i < len ; i++)
		{
			query.setParameter(i + "" , params[i]);
		}
		// 执行分页,并返回查询结果
		return query.setFirstResult((pageNo - 1) * pageSize)
			.setMaxResults(pageSize)
			.list();
	}
}
4.显示层文件

4.1 listBooks.jsp


<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>添加图书</title>
</head>
<body>
<h3>添加图书</h3>
<s:form action="addBook">
	<s:textfield name="book.name" label="书名"/>
	<s:textfield name="book.price" label="价格"/>
	<s:textfield name="book.author" label="作者"/>
	<tr align="center">
		<td colspan="2">
		<s:submit value="添加" theme="simple"/>
		<s:reset value="重设" theme="simple"/>
		</td>
	</tr>
</s:form>
</body>
</html>
4.2 bookForm.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>添加图书</title>
</head>
<body>
<h3>添加图书</h3>
<s:form action="addBook">
	<s:textfield name="book.name" label="书名"/>
	<s:textfield name="book.price" label="价格"/>
	<s:textfield name="book.author" label="作者"/>
	<tr align="center">
		<td colspan="2">
		<s:submit value="添加" theme="simple"/>
		<s:reset value="重设" theme="simple"/>
		</td>
	</tr>
</s:form>
</body>
</html>

4.3 editForm.jsp


<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>修改图书</title>
</head>
<body>
<h3>修改图书</h3>
<s:form action="doEditBook">
	<input type="hidden" value="${book.id}"  name="id"/>
	<s:textfield name="book.name" label="书名"/>
	<s:textfield name="book.price" label="价格"/>
	<s:textfield name="book.author" label="作者"/>
	<tr align="center">
		<td colspan="2">
		<s:submit value="修改" theme="simple"/>
		<s:reset value="重设" theme="simple"/>
		</td>
	</tr>
</s:form>
</body>
</html>
实例代码到这里下载:http://download.youkuaiyun.com/detail/zhengxiaojunkite/8502635

注:本文参考《轻量级javaEE企业应用实践》的代码,进行自己改进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值