mybatis+spring3+mysql整合的webservice

  接触mybatis有段时间了,mybatis是ibatis的升级版,两者还是有些差别的,最明显的是映射的 SQL 语句与接口中的方法绑定。


今天来整合一下RT的webservice,利用xml写一个对应的包含Mapper信息的配置文件来实现。看截图里的各个package结构,先把package建立起来。



那么,整合首先从spring的applicationContext-common.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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	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.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
	http://www.springframework.org/schema/jee 
	http://www.springframework.org/schema/jee/spring-jee-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-lazy-init="true">

	<description>Spring配置</description>

	<!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入-->
	<context:component-scan base-package="com.cenyi" /> 

	<!-- 加载JDBC property文件 -->
	<context:property-placeholder location="classpath*:config/jdbc.properties" ignore-unresolvable="true"/>
	
	<!-- 连接数据库	-->
 	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		
		<!-- Connection Pooling Info -->
	<!--	<property name="initialSize" value="1" /> 初始化连接数量 --> 
		<property name="maxIdle" value="5" /><!-- 最大等待连接中的数量,设 0 为没有限制 -->
		<property name="minIdle" value="1"/><!-- 最小等待连接中的数量,设 0 为没有限制  -->
		<property name="maxActive" value="25" /><!-- 连接池的最大数据库连接数。设为0表示无限制。 -->
	<!--	<property name="maxWait" value="60000"/> 最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。  -->	
	<!--	<property name="timeBetweenEvictionRunsMillis" value="3600000" />  -->	
    <!--    <property name="minEvictableIdleTimeMillis" value="3600000" />	-->	
	<!--	<property name="removeAbandoned" value="true" />强制自我中断避免dbcp自身bug出现连接过久资源耗尽-->
    <!--    <property name="removeAbandonedTimeout" value="60" />自我中断时间秒 -->
	</bean>
	
	<!-- 数据源 事务管理器配置 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	<!-- 使用annotation定义事务  -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
	
	<!-- mybatis -->	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis-configuration.xml"/>
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
	
	<bean id="personDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.cenyi.dao.PersonDao"></property>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
	<bean id="personDaoImpl" class="com.cenyi.dao.impl.PersonDaoImpl">
		<property name="personDao" ref="personDao"></property>
	</bean>
	 
	<!-- 配置切面   -->
    <aop:config>
   		<aop:aspect id="logAspecter" ref="logAspcet">
   			<aop:pointcut id="mypointcut" expression="execution(* com.cenyi.*.service.impl.*.*(..))"/>
        </aop:aspect>
    </aop:config>

</beans>

然后一个个配置文件来web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <description>mybatis+spring+cxf整合的webservice</description>
 <display-name>mybatis+spring+cxf的webservice</display-name>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext-*.xml</param-value>
 </context-param>
 <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
 </filter-mapping>
 <listener>
  <description>启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口</description>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <listener>
  <description>负责处理由JavaBeans Introspector的使用而引起的缓冲泄露</description>
  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 </listener>
 <servlet>
  <servlet-name>cxf</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>cxf</servlet-name>
  <url-pattern>/service/*</url-pattern>
 </servlet-mapping>
 <session-config>
  <session-timeout>60</session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>
</web-app>

这里呢,我们首先在mysql数据库建立一个Person的table



然后在model package里建立po  Person.java

package com.cenyi.model;


/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:Person
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-21 下午10:50:38
 * @version: 1.0
 *    
 */
public class Person {

	private String id;
	private String name;
	private int age;
	private String birthday;
	private double hight;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public double getHight() {
		return hight;
	}
	public void setHight(double hight) {
		this.hight = hight;
	}
	
}

然后来我们的Dao接口PersonDao.java

package com.cenyi.dao;

import java.util.List;

import com.cenyi.model.Person;

/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:PersonDao
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-21 下午10:02:14
 * @version: 1.0
 *    
 */

public interface PersonDao {

	public void insertPerson(Person person);
	public void updatePerson(Person person);
	public List<Person> findPerson(String name);
	public void deletePerson(String id);
}

并且建立接口的实现类PersonDaoImpl.java

package com.cenyi.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.cenyi.dao.PersonDao;
import com.cenyi.model.Person;

/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:PersonDaoImpl
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-22 上午12:04:10
 * @version: 1.0
 *    
 */
public class PersonDaoImpl extends SqlSessionDaoSupport implements PersonDao {

	private SqlSessionTemplate sqlSessionTemplate;
	
	public SqlSessionTemplate getSqlSessionTemplate() {
		return sqlSessionTemplate;
	}

	@Resource(name="sqlSessionTemplate")  
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	public void deletePerson(String id) {
		getSqlSession().delete("com.cenyi.dao.PersonDao.deletePerson", id);
	}

	public List<Person> findPerson(String name) {
		return getSqlSession().selectList("com.cenyi.dao.PersonDao.findPerson", name);
	}

	public void insertPerson(Person person) {
		getSqlSession().insert("com.cenyi.dao.PersonDao.insertPerson", person);
	}

	public void updatePerson(Person person) {
		getSqlSession().update("com.cenyi.dao.PersonDao.updatePerson", person);
	}

}

然后我们要写一个包含mapper信息的xml了PersonMapper.xml(如之前提到的,还可以用另外一种定义一个Mapper接口、通过注解辅助的方式来实现)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 

<mapper namespace="com.cenyi.dao.PersonDao">

	<insert id="insertPerson" parameterType="Person" useGeneratedKeys="true" keyColumn="id">
		insert into Person(id, name, age, birthday, hight, time) values(#{id}, #{name}, #{age}, #{birthday}, #{hight}, now())
	</insert>
	
	<update id="updatePerson" parameterType="Person">
		update Person 
		<set>
			<if test="name != null">name=#{name},</if>
			<if test="age != null">age=#{age},</if>
			<if test="birthday != null">birthday=#{birthday},</if>
			<if test="hight != null">hight=#{hight}</if>
		</set>
		 where id=#{id}
	</update>
	
	<resultMap type="Person" id="personMap">
		<result column="id" property="id" />
		<result column="name" property="name" />
		<result column="age" property="age" />
		<result column="birthday" property="birthday" />
		<result column="hight" property="hight" />
	</resultMap>
	
	<select id="findPerson" parameterType="Person" resultType="list" resultMap="personMap">
		select * from Person where 1=1 and name=#{name}
	</select>
	
	<delete id="deletePerson" parameterType="string">
		delete from Person where id=#{id}
	</delete>
</mapper>

紧接着,来写service层PersonService.java。

package com.cenyi.service;

import java.util.List;

import com.cenyi.model.Person;

/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:PersonService
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-21 下午11:42:04
 * @version: 1.0
 *    
 */
public interface PersonService {

	public void insertPerson(Person person);
	public void updatePerson(Person person);
	public List<Person> findPerson(String name);
	public void deletePerson(String id);
}

和其实现类PersonServiceImpl.java

package com.cenyi.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cenyi.dao.PersonDao;
import com.cenyi.model.Person;
import com.cenyi.service.PersonService;

/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:PersonServiceImpl
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-21 下午11:42:37
 * @version: 1.0
 *    
 */

@Service
@Transactional
public class PersonServiceImpl implements PersonService {
	
	@Resource
	private PersonDao personDao;
	
	public PersonDao getPersonDao() {
		return personDao;
	}
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	public void deletePerson(String id) {
		personDao.deletePerson(id);
	}

	public List<Person> findPerson(String name) {
		return personDao.findPerson(name);
	}

	public void insertPerson(Person person) {
		personDao.insertPerson(person);
	}

	public void updatePerson(Person person) {
		personDao.updatePerson(person);
	}

}

最后呢,来写webservice的接口了,

package com.webservice;

import com.cenyi.model.Person;

/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:myWebservice
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-22 上午08:40:22
 * @version: 1.0
 *    
 */

public interface MyWebservice {
	public String pushData(Person person);
}

这里我使用了线程来操作的,算是对线程的一个练习吧。

package com.webservice.impl;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.springframework.stereotype.Component;

import com.cenyi.model.Person;
import com.cenyi.service.PersonService;
import com.webservice.MyWebservice;

/**   
 *    
 * @项目名称:mybatisWebservice
 * @类名称:MyWebserviceImpl
 * @类描述:
 * @创建人:cenyi
 * @创建时间:2015-3-22 上午09:10:41
 * @version: 1.0
 *    
 */

@WebService(targetNamespace="impl.webservice.com", portName="MyWebserviceImplPort", serviceName="MyWebserviceImplSerivce")
@Component
public class MyWebserviceImpl implements MyWebservice {

	@Resource
	private PersonService personService;
	
	public String pushData(Person person) {
		StringBuffer sb = new StringBuffer("");
		CrudThread ct = new CrudThread(personService, sb, person);
		Thread t = new Thread(ct);
		t.start();
		System.err.println(sb.toString());
		return sb.toString();
	}

}

class CrudThread implements Runnable{
	
	private PersonService personService;
	public StringBuffer sb;
	public Person person;
	
	public CrudThread(PersonService personService, StringBuffer sb, Person person) {
		this.personService = personService;
		this.sb =sb;
		this.person = person;
	}

	public void run() {
		try {
			sb.append("进入了webservice了...\r");
			Thread.sleep(3000);
			//insert
			sb.append("开始添加信息");
			Thread.sleep(3000);
//		Person person = new Person();
//		person.setAge(30);
//		person.setBirthday("1990-1-1");
//		person.setHight(175.12D);
//		person.setName("cenyi");
			personService.insertPerson(person);
			sb.append("完成添加信息\r");
			Thread.sleep(3000);
			//query
			Person p = personService.findPerson("cenyi").get(0);
			System.out.println("insert完成:"+p.getId()+", "+p.getName()+", "+p.getAge()+", "+p.getHight()+", "+p.getBirthday().toString());
			//update
			sb.append("开始修改信息\r");
			Thread.sleep(3000);
			p.setAge(26);
			p.setName("Tom");
			p.setHight(172D);
			personService.updatePerson(p);
			sb.append("完成修改信息\r");
			Thread.sleep(3000);
			//query
			Person per = personService.findPerson(p.getName()).get(0);
			System.out.println("update完成:"+per.getId()+", "+per.getName()+", "+per.getAge()+", "+per.getHight()+", "+per.getBirthday().toString());
			//delete
//			sb.append("开始删除信息\r");
//			personService.deletePerson(p.getId());
//			sb.append("完成删除信息\r");
//			Thread.sleep(3000);
//			//insert
//			sb.append("再次insert信息\r");
//			personService.insertPerson(person);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


最后我们需要建一个client来验证这个webservice了。生成客户的方法呢,可以直接在myeclipse上实现,具体的方法请大家查看我的博文里有篇详细的spring+ibatis+mysql整合的webservice,里边有详细的截图来告知大家如何生成webservice的client。最终测试ok的。





相应的源码地址客户端的是:http://download.csdn.net/detail/cenyi2012/8523995

服务端的是:http://download.csdn.net/detail/cenyi2012/8524013

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值