ibatis结合Struts2.0, Spring实现增,删,改,查的基本功能

ibatis结合Struts2.0, Spring实现增,删,改,查的基本功能

1.JavaBean:Person.java

   

package com.baoz.ibatis.entity;

import java.util.Date;

public class Person {
	private Integer id;

	private String firstName;

	private String lastName;

	private Date birthDate;

	private Double weight;

	private Double height;

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public double getHeight() {
		return height;
	}

	public void setHeight(double height) {
		this.height = height;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Double getWeight() {
		return weight;
	}

	public void setWeight(Double weight) {
		this.weight = weight;
	}

	public void setHeight(Double height) {
		this.height = height;
	}
}

  

 

 

 

2.ibatis映射配置:

 

<?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="person">
	<typeAlias alias="Person" type="com.baoz.ibatis.entity.Person"/>
	
	<select id="readForId" resultClass="Person" parameterClass="java.lang.Integer">
		select * from person where id=#value#
	</select>
	
	<select id="queryList" resultClass="Person">
		select * from person
	</select>
	
	<insert id="add" parameterClass="Person" >
		insert into person (firstName, lastName, birthDate, weight, height) values(#firstName#, #lastName#, #birthDate#, #weight#, #height#)
	</insert>
	
	<update id="update" parameterClass="Person">
		update person set firstName=#firstName#, lastName=#lastName#, birthDate=#birthDate#, weight=#weight#, height=#height# where id=#id#
	</update>
	
	<delete id="delete" parameterClass="java.lang.Integer">
		delete from person where id=#value#
	</delete>
	
	
</sqlMap>

 

 

 

 

 

3.ibatis配置实例

   

<?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>
	<settings useStatementNamespaces="true"/>
	<sqlMap resource="com/baoz/ibatis/xmls/person.xml"/>
</sqlMapConfig>

  

 

 

4.struts2.0的配置文件:

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.i18n.encoding" value="UTF-8" />
	
  	<include file="struts-default.xml"></include>
  	<package name="myAction" extends="struts-default">
    	<action name="person" class="com.baoz.ibatis.action.PersonAction">
      		<result name="list">/personList.jsp</result>
      		<result name="add">/personEdit.jsp</result>
    	</action>
  	</package>
</struts>

 

 

 

 

 

 

  

5.spring的配置文件

 

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">


	<context:annotation-config />
	<context:component-scan base-package="com.baoz" />
	<bean
		class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />	
	<bean id="myDataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver">
		</property>
		<property name="url"
			value="jdbc:mysql://127.0.0.1:3306/ibatisDB">
		</property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>

	<bean id="myIbatis"
		class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation"
			value="sqlMapConfigExample.xml">
		</property>
		<property name="dataSource" ref="myDataSource"></property>
	</bean>
	<bean id="personDao" class="com.baoz.ibatis.dao.PersonDao">
		<property name="sqlMapClient" ref="myIbatis"></property>
	</bean>

	<bean id="personService" name="personService" class="com.baoz.ibatis.service.PersonService" scope="singleton">
	</bean>
</beans>

 

 

6.怎样用ibatis的dao:

  

package com.baoz.ibatis.dao;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.baoz.ibatis.entity.Person;

public class PersonDao extends SqlMapClientDaoSupport {
	public Person readForId(int id){
		return (Person)getSqlMapClientTemplate().queryForObject("person.readForId", id);
	}
	
	public List queryList(){
		return getSqlMapClientTemplate().queryForList("person.queryList");
	}
	
	public void add(Person person){
		getSqlMapClientTemplate().insert("person.add", person);
	}
	
	public void update(Person person){
		getSqlMapClientTemplate().update("person.update", person);
	}
	
	public void delete(int id){
		getSqlMapClientTemplate().delete("person.delete", id);
	}
}

 

7.Service:

package com.baoz.ibatis.IService;

import java.util.List;

import com.baoz.ibatis.entity.Person;

public interface IPersonService {
	public void insert(Person person);
	
	public List queryList();

	public Person readForid(int id);
	
	public void update(Person person);
	
	public void delete(int id);

}

package com.baoz.ibatis.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.baoz.ibatis.IService.IPersonService;
import com.baoz.ibatis.dao.PersonDao;
import com.baoz.ibatis.entity.Person;

public class PersonService implements IPersonService {
	@Autowired
	@Qualifier("personDao")
	private PersonDao personDao;
	
	public Person readForid(int id){
		return personDao.readForId(id);
	}
	
	public void insert(Person person){
		personDao.add(person);
	}
	
	public void add(Person person){
		personDao.add(person);
	}
	
	public void update(Person person){
		personDao.update(person);
	}
	
	public void delete(int id){
		personDao.delete(id);
	}

	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	public List queryList() {
		return personDao.queryList();
		
	}
}

 

 

 

8.Action:

package com.baoz.ibatis.action;

import java.util.List;

import org.apache.commons.beanutils.MethodUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.baoz.ibatis.IService.IPersonService;
import com.baoz.ibatis.entity.Person;
import com.opensymphony.xwork2.Action;

public class PersonAction implements Action {
	private IPersonService personService;
	
	private List list;
	
	private Person person;
	
	private String method;
	
	private String id;
	
	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}
	
	public String execute() throws Exception {
		if(method != null && !method.equals("")){
			return (String)MethodUtils.invokeMethod(this, method, new Object[]{});
		}
		return null;
	}
	
	public String list(){
		list = this.getPersonService().queryList();
		return "list";
	}
	
	public String addOrEdit(){
		if(person.getId() != null ){
			this.getPersonService().update(person);
		}else{
			this.getPersonService().insert(person);
		}
		return list();
	}
	
	public String toEdit(){
		if(id != null && !id.equals("")){
			int editId = Integer.parseInt(id);
			person = getPersonService().readForid(editId);
		}
		return "add";
	}
	
	public String delete(){
		if(id != null && !id.equals("")){
			int deleteId = Integer.parseInt(id);
			this.getPersonService().delete(deleteId);
		}
		return list();
	}

	public IPersonService getPersonService() {
		if(personService == null){
			ApplicationContext context = new ClassPathXmlApplicationContext("bean_main.xml");
			personService=(IPersonService)context.getBean("personService");
		}
		return personService;
	}

	public void setPersonService(IPersonService personService) {
		this.personService = personService;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}
}

 

9.JSP:

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>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
    <a href="person.action?method=list">用户管理</a>
  </body>
</html>

 

 

personList.jsp:

 

 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>My JSP 'personList.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head> 
  <body>
    <table align="center" border="1">
    	<tr align="center"><td align="center" colspan="6">用户管理</td></tr>
    	<tr align="center"><td align="right" colspan="6"><s:a href="personEdit.jsp">用户新增</s:a></td></tr>
    	<tr align="center">
    		<td align="center">名字</td>
    		<td align="center">姓氏</td>
    		<td align="center">出生日期</td>
    		<td align="center">体重(Kg)</td>
    		<td align="center">身高(cm)</td>
    		<td align="center">操作</td>
    	</tr>
  		<s:iterator id="person" value="list">
  		<tr align="center">
    		<td align="center"><s:property value="firstName"/></td>
    		<td align="center"><s:property value="lastName"/></td>
    		<td align="center"><s:property value="birthDate"/></td>
    		<td align="center"><s:property value="weight"/></td>
    		<td align="center"><s:property value="height"/></td>
    		<td align="center">
    			<a href='<s:url action="person"><s:param name="method">toEdit</s:param><s:param name="id" value="id"></s:param></s:url>'>编辑</a>&nbsp;&nbsp;
				<a href='<s:url action="person"><s:param name="method">delete</s:param><s:param name="id" value="id"></s:param></s:url>'>删除</a></td>
    	</tr>
  		</s:iterator>
  	</table>
  </body>
</html>
 

 

 

personEdit.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	
  <s:head theme="ajax"/>
  <head>
  	
    <base href="<%=basePath%>">
    <title>My JSP 'personEdit.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
    <s:form action="person.action?method=addOrEdit">
    	<s:hidden name="person.id"></s:hidden>
    	<table align="center" border="1">
    		<tr align="center"><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;用户新增</td></tr>
    		<tr align="center"><td><s:textfield name="person.firstName" label="名字"></s:textfield></td></tr>
    		<tr align="center"><td><s:textfield name="person.lastName" label="姓氏"></s:textfield><br/></td></tr>
    		<tr align="center"><td><s:datetimepicker name="person.birthDate" toggleType="fade" label="出生日期"></s:datetimepicker><br/></td></tr>
    		<tr align="center"><td><s:textfield name="person.weight" label="体重"></s:textfield><br/></td></tr>
    		<tr align="center"><td><s:textfield name="person.height" label="身高"></s:textfield><br/></td></tr>
    		<tr align="center"><td><s:submit value="提交"></s:submit></td></tr>
    	</table>
    	<br/>
    </s:form>
  </body>
</html>

 

 

10.web.xml

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">	
	<!-- context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/classes/bean_main.xml
		</param-value>
	</context-param>
	 --> 
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/classes/log4j.properties</param-value>
	</context-param>
	
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.FilterDispatcher
		</filter-class>	 
	</filter>
	
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	
	<!-- listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	 -->
	  
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

 11.log4j.properties

log4j.rootLogger=info,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
log4j.logger.com.wehave=DEBUG
# log4j.logger.org.springframework=DEBUG
# SqlMap logging configuration...
# log4j.logger.com.ibatis=DEBUG
# log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
# log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
# log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=info
log4j.logger.java.sql.PreparedStatement=info
log4j.logger.java.sql.ResultSet=info
log4j.logger.javax.sql=info

 

你可能感兴趣的:(spring,log4j,bean,struts,ibatis)