说明:
使用 spring2.5 +ibatis2.3.4+oscache2.4+struts2+oracle
建表
create table STUDENT
(
SID NUMBER(8) primary key not null,
SNAME VARCHAR2(20) not null,
MAJOR VARCHAR2(100),
BIRTH DATE,
SCORE NUMBER(6,2)
)
-- Create sequence
create sequence STUDENT_SEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 21
increment by 1
cache 20;
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 采用c3p0数据源 这个是在企业中用的比较多的一个数据源 -->
<!-- destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="user" value="luob"/>
<property name="password" value="luob"/>
<!-- 连接池中的最大连接数 -->
<property name="maxPoolSize" value="150"/>
<!-- 连接池中的最小连接数 -->
<property name="minPoolSize" value="1"></property>
<!-- 初始化连接池中的 连接数,取值 在 minPoolSize 和 maxPoolSize 之间,default:3-->
<property name="initialPoolSize" value="3"/>
<!-- 最大空闲时间,60s内该连接没有被使用则被丢弃,若为0 永不丢弃.default:0 -->
<property name="maxIdleTime" value="60"/>
<!-- 当连接数不够时,每次同时创建多少个连接 -->
<property name="acquireIncrement" value="1"/>
<!-- 每60s检查连接池中的所有空间连接,如果没有被使用,就被放弃, default:0 -->
<property name="idleConnectionTestPeriod" value="60"/>
</bean>
<!-- 从c3p0数据源中抽取出JDBC的代理对象-->
<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.C3P0NativeJdbcExtractor" lazy-init="true" />
<!--9i: org.springframework.jdbc.support.lob.OracleLobHandler -->
<!--10g以后:org.springframework.jdbc.support.lob.DefaultLobHandler(mysql,DB2等都可以用这个) -->
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true">
<!-- 9i: 指定操作lob类型数据的jdbc代理对象 如果上面的 lobHandler 换了下面的就不需要了 -->
<property name="nativeJdbcExtractor">
<ref local="nativeJdbcExtractor" />
</property>
</bean>
<!--==================================================== -->
<!-- ////让spring来管理batis 的SqlMapClient对象 //////////-->
<!--==================================================== -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="lobHandler" ref="lobHandler"/>
<property name="configLocation"><value>classpath:SqlMapConfig.xml</value></property>
</bean>
<!--=============================== -->
<!-- //// batis事务代理配置 /////////-->
<!--=============================== -->
<!-- 使用jdbc 来管理事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 定义DAO bean的事务代理-->
<bean id="templatesDAO"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean ">
<!-- 为事务代理bean注入事务管理器-->
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<!-- 设置事务属性-->
<property name="transactionAttributes">
<props>
<!-- 所有以add开头的方法,采用required的事务策略,并且只读-->
<prop key="add*">PROPAGATION_REQUIRED</prop>
<!-- 所有以mod开头的方法,采用required的事务策略,并且只读-->
<prop key="mod*">PROPAGATION_REQUIRED</prop>
<!-- 所有以del开头的方法,采用required的事务策略,并且只读-->
<prop key="del*">PROPAGATION_REQUIRED</prop>
<!-- 其他方法,采用required的事务策略 -->
<prop key="*">readOnly</prop>
</props>
</property>
<!-- 为事务代理bean设置目标bean -->
<property name="target">
<!-- 采用嵌套bean配置目标bean-->
<bean class="test.dao.impl.TaoTemplatesDAOImpl">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
</property>
</bean>
<!-- =============================== -->
<!-- ///////// dao 的配置 /////-->
<!-- =============================== -->
<bean id="studentDAO" class="com.ibatis.student.IStudentDAOImpl">
<property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
<!-- =============================== -->
<!-- ///// Serivce 的配置 /////-->
<!-- =============================== -->
<bean id="studentService" class="com.ibatis.student.IStudentServiceImpl">
<property name="studentDAO" ref="studentDAO"/>
</bean>
</beans>
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- 使用spring之后,数据源的配置移植到了spring上,所以IBATIS本身的配置可以取消 -->
<!-- 对 ibatis 的设置 -->
<settings maxRequests="256" maxSessions="64" maxTransactions="16"
enhancementEnabled="true" lazyLoadingEnabled="true" useStatementNamespaces="false" />
<!-- List the SQL Map XML files. They can be loaded from the
classpath, as they are here (com.domain.data...) -->
<sqlMap resource="com/ibatis/student/Student.xml"/>
<!-- List more here...
<sqlMap resource="com/mydomain/data/Order.xml"/>
<sqlMap resource="com/mydomain/data/Documents.xml"/>
-->
</sqlMapConfig>
Student.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="studentSqlMap">
<!-- 别名 就像java中 import packageName -->
<typeAlias alias="Student" type="com.ibatis.student.Student"/>
<!-- 使用 OSCACHE 缓存机制 -->
<cacheModel id="student-cache" type="OSCACHE">
<flushInterval hours="24" />
<flushOnExecute statement="queryAllStudent" />
<property name="size" value="1000" />
</cacheModel>
<select id="queryAllStudent" resultClass="Student">
select * from student
</select>
<select id="queryStudentById" parameterClass="int" resultClass="Student">
select * from student where sid=#sid#
</select>
<!-- 这个里面的 占位符 就不能乱写了 因为会调用 Student 的 getSid ...getSname() .. -->
<insert id="addStudent" parameterClass="Student">
insert into student(sid,sname,major,birth,score)
values (#sid#,#sname#,#major#,#birth#,#score#)
</insert>
<!-- #sid# 这个 只是一个占位符 可以更改的 -->
<delete id="deleteStudentById" parameterClass="int">
delete from student where sid=#sid#
</delete>
<update id="updateStudent" parameterClass="Student">
update student
set
sname=#sname#,
major=#major#,
birth=#birth#,
score=#score#
where sid=#sid#
</update>
<!-- 如果参数 要拼接成一个表达式 就要将# 换成 $ -->
<select id="queryStudentByName" parameterClass="String" resultClass="Student">
select sid,sname,major,birth,score from student where sname like '$sname$'
</select>
<!-- Student 不区分大小写的 -->
<insert id="insertStudentBySequence" parameterClass="Student">
<selectKey resultClass="int" keyProperty="sid">
select STUDENT_SEQ.nextVal from dual
</selectKey>
insert into student(sid,sname,major,birth,score)
values (#sid#,#sname#,#major#,#birth#,#score#)
</insert>
</sqlMap>
Student.java
package com.ibatis.student;
import java.util.Date;
public class Student {
private int sid;
private String sname;
private String major;
private Date birth;
private float score;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public String toString() {
// TODO Auto-generated method stub
String content = "sid:" + sid + "\tsname:" + sname + "\tmajor:" + major
+ "\tbirth:" + birth + "\tscore=" + score;
return content;
}
}
IStudentDAO.java
package com.ibatis.student;
import java.util.List;
public interface IStudentDAO {
public void addStudent(Student student);
//使用自动增长 主键
public void addStudentBySequence(Student student);
public void delStudentById(int id);
public void updStudentById(Student student);
public List<Student> queryAllStudent();
//使用模糊查询
public List<Student> queryStudentByName(String name);
public Student queryStudentById(int id);
}
IStudentDAOImpl.java
package com.ibatis.student;
import java.io.IOException;
import java.io.Reader;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import com.ibatis.sqlmap.client.SqlMapClient;
public class IStudentDAOImpl extends SqlMapClientDaoSupport implements IStudentDAO {
//private static SqlMapClient sqlMapClient=null;
/*static{
try {
Reader reader=com.ibatis.common.resources.Resources.getResourceAsReader("SqlMapConfig.xml");
sqlMapClient=com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
public void addStudent(Student student) {
// TODO Auto-generated method stub
student=(Student)getSqlMapClientTemplate().insert("addStudent", student);
System.out.println(student.getSid());
}
public void addStudentBySequence(Student student) {
// TODO Auto-generated method stub
getSqlMapClientTemplate().insert("insertStudentBySequence", student);
}
public void delStudentById(int id) {
// TODO Auto-generated method stub
try {
int rows=getSqlMapClientTemplate().delete("deleteStudentById", id);
System.out.println(rows);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
public List<Student> queryAllStudent() {
// TODO Auto-generated method stub
List<Student> studentList=null;
try {
studentList=getSqlMapClientTemplate().queryForList("queryAllStudent");
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return studentList;
}
public Student queryStudentById(int id) {
Student student=null;
try {
student=(Student)getSqlMapClientTemplate().queryForObject("queryStudentById",id);
} catch (Exception e) {
e.printStackTrace();
}
return student;
}
public List<Student> queryStudentByName(String name) {
// TODO Auto-generated method stub
List<Student> studentList=null;
try {
studentList=getSqlMapClientTemplate().queryForList("queryStudentByName", name);
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return studentList;
}
public void updStudentById(Student student) {
// TODO Auto-generated method stub
try {
int rows=getSqlMapClientTemplate().update("updateStudent", student);
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IStudentServiceImpl.java
package com.ibatis.student;
import java.util.List;
public class IStudentServiceImpl implements IStudentService {
private IStudentDAO studentDAO;
public void setStudentDAO(IStudentDAO studentDAO) {
this.studentDAO = studentDAO;
}
public void addStudent(Student student) {
// TODO Auto-generated method stub
studentDAO.addStudent(student);
}
public void addStudentBySequence(Student student) {
// TODO Auto-generated method stub
studentDAO.addStudentBySequence(student);
}
public void delStudentById(int id) {
// TODO Auto-generated method stub
studentDAO.delStudentById(id);
}
public List<Student> queryAllStudent() {
// TODO Auto-generated method stub
return studentDAO.queryAllStudent();
}
public Student queryStudentById(int id) {
// TODO Auto-generated method stub
return studentDAO.queryStudentById(id);
}
public List<Student> queryStudentByName(String name) {
// TODO Auto-generated method stub
return studentDAO.queryStudentByName(name);
}
public void updStudentById(Student student) {
// TODO Auto-generated method stub
studentDAO.updStudentById(student);
}
}
Test.java
package com.ibatis.student;
import java.sql.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String [] args){
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
IStudentService studentService=(IStudentService)context.getBean("studentService");
//1.
for (Student student : studentService.queryAllStudent()) {
System.out.println(student);
}
//2.
// System.out.println(dao.queryStudentById(1));
//3.
// Student student=new Student();
// student.setSid(5);
// student.setSname("admin");
// student.setScore(100);
// student.setMajor("Games");
// student.setBirth(Date.valueOf("2008-08-08"));
//
// dao.addStudent(student);
//4.
// dao.delStudentById(1);
//5.
// Student student=new Student();
// student.setSid(2);
// student.setSname("luob");
// student.setScore(50);
// student.setMajor("Games");
// student.setBirth(Date.valueOf("2008-08-08"));
// dao.updStudentById(student);
//6.
// for (Student student : dao.queryStudentByName("l%")) {
// System.out.println(student);
// }
//7.
/*Student student=new Student();
student.setSid(2);
student.setSname("SCOTT");
student.setScore(50);
student.setMajor("paly Games");
student.setBirth(Date.valueOf("2008-08-08"));
studentService.addStudentBySequence(student);
System.out.println("success");*/
}
}
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>
<package name="student" namespace="/student" extends="struts-default">
<action name="userLogin" class="com.ibatis.student.action.StudentAction" method="login">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
BaseAction.java
package com.ibatis.student.common;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport{
public Object getServiceBean(String beanId){
ServletContext sc=ServletActionContext.getServletContext();
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(sc);
return ctx.getBean(beanId);
}
public HttpServletRequest getRequest(){
return ServletActionContext.getRequest();
}
public HttpServletResponse getResponse(){
return ServletActionContext.getResponse();
}
public Map<String, Object> getSession() {
ActionContext act=ActionContext.getContext();
return act.getSession();
}
}
StudentAction.java
package com.ibatis.student.common;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport{
public Object getServiceBean(String beanId){
ServletContext sc=ServletActionContext.getServletContext();
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(sc);
return ctx.getBean(beanId);
}
public HttpServletRequest getRequest(){
return ServletActionContext.getRequest();
}
public HttpServletResponse getResponse(){
return ServletActionContext.getResponse();
}
public Map<String, Object> getSession() {
ActionContext act=ActionContext.getContext();
return act.getSession();
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Ibatis + Spring + Struts2 </title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath}/student/userLogin.action" method="post">
用户名:<input type="text" name="userName"/>
密码:<input type="password" name="password"/>
<input type="submit" value="提交"/>
</form>
${sesssion_msg}
${request_msg}
</body>
</html>