---
title: "WebService CXF学习（高级篇2）：CXF+Spring+Hibernate"
author: "iaspecwang"
date: "2013-08-11T20:53:36Z"
tags: []
categories: ["企业架构"]
slug: "webservice-cxf-2-cxf-spring-hibernate"
draft: true
lastmod: "2013-08-11T20:53:36Z"
id: 1922363
url: "https://iaspecwang.iteye.com/blog/1922363"
---

前一节仅仅只讲了与Spring整合，没有涉及到数据库，而且是直接将Java象传递到服务端。这一节我起到一个回顾前面章节的作用。用在客户端运用JABX将JAVA对象编组成XML文件，在客户端将XML解组成JAVA并存入数据库。下面我们就着手开发这个Demo:   
    **服务端开发**   
    第一步，编写数据资源层相关接口   
    DAO编写：   
   

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

1. public interface HibernateDao {
2. public void save(UserInfo object);
3. public void delete(UserInfo object);
4. public void update(UserInfo object);
5. public UserInfo get(int id);
6. }

    DAO实现类： 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. public class HibernateDaoImpl extends HibernateDaoSupport implements HibernateDao {
02. public void delete(UserInfo object) {
03. this.getHibernateTemplate().delete(object);
04. }
05. public void save(UserInfo object) {
06. this.getHibernateTemplate().save(object);
07. }
08. public void update(UserInfo object) {
09. this.getHibernateTemplate().update(object);
10. }
11. public UserInfo get(int id) {
12. return (UserInfo) this.getHibernateTemplate().get(UserInfo.class, id);
13. }
14. }

      实体对象： 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. @Entity
02. @Table(name = "userinfo")
03. public class UserInfo implements java.io.Serializable {
04. private static final long serialVersionUID = 2281022190032353574L;
05. @Id
06. @GeneratedValue(strategy = GenerationType.IDENTITY)
07. private Integer id;
08. private String name;
09. private Integer age;
10. private Integer address;
11. public UserInfo() {
12. }
13. public UserInfo(String name, Integer age) {
14. this.name = name;
15. this.age = age;
16. }
17. public UserInfo(String name, Integer age, Integer address) {
18. this.name = name;
19. this.age = age;
20. this.address = address;
21. }
22. public Integer getId() {
23. return this.id;
24. }
25. public void setId(Integer id) {
26. this.id = id;
27. }
28. public String getName() {
29. return this.name;
30. }
31. public void setName(String name) {
32. this.name = name;
33. }
34. public Integer getAge() {
35. return this.age;
36. }
37. public void setAge(Integer age) {
38. this.age = age;
39. }
40. public Integer getAddress() {
41. return this.address;
42. }
43. public void setAddress(Integer address) {
44. this.address = address;
45. }
46. }

      第二步：业务逻辑层接口编写   
      业务逻辑接口： 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

1. @WebService
2. public interface IService {
3. //public void save(@WebParam(name="info")String xml);
4. public void save(@WebParam(name="dto")UserInfoDTO dto,@WebParam(name="flag")boolean flag);
5. public void update(@WebParam(name="info")String xml);
6. public void delete(@WebParam(name="id")int id);
7. public @WebResult(name="String")String get(@WebParam(name="id")int id);
8. }

     接口实现类： 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. @WebService
02. public class ServiceImpl implements IService {
03. private Logger log = LoggerFactory.getLogger(ServiceImpl.class);
04. private HibernateDao dao;
05. //  public void setDao(HibernateDao dao) {
06. //      this.dao = dao;
07. //  }
08. public void delete(int id) {
09. log.info("delete id is {} user"+id);
10. //UserInfo userInfo = (UserInfo)object;
11. //log.info("this username is:"+userInfo.getName());
12. //log.info("delete {} information..."+userInfo.getName());
13. //dao.delete(userInfo);
14. }
15. //  public void save(String xml) {
16. //      //UserInfo userInfo = (UserInfo)object;
17. //      log.info("add {} user..."+xml);
18. //      //dao.save(userInfo);
19. //      System.out.println("ssss");
20. //  }
21. public void save(UserInfoDTO dto,boolean flag) {
22. System.out.println("name:"+dto.getName());
23. }
24. public void update(String xml){
25. ApplicationContext context = new ClassPathXmlApplicationContext(
26. "applicationContext-resources.xml");
27. this.dao = (HibernateDao)context.getBean("dao");
28. try {
29. JAXBContext jaxbContext = JAXBContext.newInstance("com.itdcl.model");
30. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
31. StringReader reader = new StringReader(xml);
32. Customers cus = (Customers)unmarshaller.unmarshal(reader);
33. Customer cust = cus.getCustomer();
34. UserInfo userInfo = new UserInfo();
35. System.out.println("Address:"+cust.getAddress());
36. userInfo.setAddress(cust.getAddress());
37. System.out.println("Age:"+cust.getAge());
38. userInfo.setAge(Integer.valueOf(cust.getAge()));
39. System.out.println("Name:"+cust.getName());
40. //userInfo.setId(2);
41. userInfo.setName(cust.getName());
42. dao.save(userInfo);
43. } catch (JAXBException e) {
44. e.printStackTrace();
45. }
46. }
47. public String get(int id){
48. //return dao.get(id);
49. return null;
50. }
51. }

     DAO与Service接口配置： 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:aop="http://www.springframework.org/schema/aop"
05. xmlns:tx="http://www.springframework.org/schema/tx"
06. xmlns:jaxws="http://cxf.apache.org/jaxws"
07. xsi:schemaLocation="
08. http://cxf.apache.org/jaxws
09. http://cxf.apache.org/schemas/jaxws.xsd
10. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
11. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
12. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"&gt;
13. &lt;!--\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*Hibernate数据库持久层配置文件\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*--&gt;
14. &lt;bean id="propertyConfigurer"
15. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
16. &lt;property name="locations"&gt;
17. &lt;list&gt;
18. &lt;value&gt;classpath:jdbc.properties&lt;/value&gt;
19. &lt;/list&gt;
20. &lt;/property&gt;
21. &lt;/bean&gt;
22. &lt;bean id="dataSource"
23. class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
24. &lt;property name="driverClassName" value="${driverClassName}" /&gt;
25. &lt;property name="url" value="${jdbc.url}" /&gt;
26. &lt;property name="username" value="${jdbc.username}" /&gt;
27. &lt;property name="password" value="${jdbc.password}" /&gt;
28. &lt;/bean&gt;
29. &lt;bean id="sessionFactory"
30. class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
31. &lt;property name="dataSource"&gt;
32. &lt;ref local="dataSource" /&gt;
33. &lt;/property&gt;
34. &lt;property name="hibernateProperties"&gt;
35. &lt;props&gt;
36. &lt;prop key="hibernate.dialect"&gt;
37. ${hibernate.dialect}
38. &lt;/prop&gt;
39. &lt;prop key="hibernate.show\_sql"&gt;${show\_sql}&lt;/prop&gt;
40. &lt;prop key="hibernate.format\_sql"&gt;${format\_sql}&lt;/prop&gt;
41. &lt;!-- 缓存设置 --&gt;
42. &lt;prop key="cache.use\_query\_cache"&gt;
43. ${cache.use\_query\_cache}
44. &lt;/prop&gt;
45. &lt;prop key="cache.use\_second\_level\_cache"&gt;
46. ${cache.use\_second\_level\_cache}
47. &lt;/prop&gt;
48. &lt;prop key="cache.provider\_class"&gt;
49. ${cache.provider\_class}
50. &lt;/prop&gt;
51. &lt;!-- C3P0连接池配置 --&gt;
52. &lt;prop key="c3p0.acquire\_increment"&gt;
53. ${c3p0.acquire\_increment}
54. &lt;/prop&gt;
55. &lt;prop key="c3p0.max\_statements"&gt;
56. ${c3p0.max\_statements}
57. &lt;/prop&gt;
58. &lt;prop key="c3p0.min\_size"&gt;${c3p0.min\_size}&lt;/prop&gt;
59. &lt;prop key="c3p0.max\_size"&gt;${c3p0.max\_size}&lt;/prop&gt;
60. &lt;prop key="c3p0.timeout"&gt;${c3p0.timeout}&lt;/prop&gt;
61. &lt;prop key="c3p0.idle\_test\_period"&gt;
62. ${c3p0.idle\_test\_period}
63. &lt;/prop&gt;
64. &lt;/props&gt;
65. &lt;/property&gt;
66. &lt;property name="namingStrategy"&gt;
67. &lt;bean class="org.hibernate.cfg.ImprovedNamingStrategy" /&gt;
68. &lt;/property&gt;
69. &lt;property name="packagesToScan" value="com.itdcl.pojo" /&gt;
70. &lt;/bean&gt;
71. &lt;bean id="dao" class="com.itdcl.dao.HibernateDaoImpl"&gt;
72. &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
73. &lt;/bean&gt;
74. &lt;/beans&gt;

     WebService接口发布： 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:jaxws="http://cxf.apache.org/jaxws"
05. xsi:schemaLocation="
06. http://www.springframework.org/schema/beans
07. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
08. http://cxf.apache.org/jaxws
09. http://cxf.apache.org/schemas/jaxws.xsd"&gt;
10. &lt;import resource="classpath:META-INF/cxf/cxf.xml" /&gt;
11. &lt;import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /&gt;
12. &lt;import resource="classpath:META-INF/cxf/cxf-servlet.xml" /&gt;
13. &lt;bean id="serverUserInfo" class="com.itdcl.model.UserInfoDTO" /&gt;
14. &lt;jaxws:endpoint id="helloWorld"
15. implementor="com.itdcl.service.HelloWorldImpl" address="/HelloWorld" /&gt;
16. &lt;jaxws:endpoint id="myTest"
17. implementor="com.itdcl.service.MyTestImpl" address="/MyTest" /&gt;
18. &lt;jaxws:endpoint id="service"
19. implementor="com.itdcl.service.ServiceImpl" address="/Service"&gt;
20. &lt;!--  jaxws:serviceFactory&gt;
21. &lt;ref bean="jaxWsServiceFactoryBean" /&gt;
22. &lt;/jaxws:serviceFactory&gt;--&gt;
23. &lt;/jaxws:endpoint&gt;
24. &lt;bean id="jaxWsServiceFactoryBean"
25. class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean"&gt;
26. &lt;property name="wrapped" value="true" /&gt;
27. &lt;property name="dataBinding" ref="aegisBean" /&gt;
28. &lt;/bean&gt;
29. &lt;bean id="aegisBean"
30. class="org.apache.cxf.aegis.databinding.AegisDatabinding" /&gt;
31. &lt;/beans&gt;

    第三步：服务端程序编写了，打包部署 

    **客户端开发**   
    第一步：WebService客户端生成，可以手工编写。这里我就通过配置Ant文件来生成WebService客户端: 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0"?&gt;
02. &lt;project name="cxf" basedir="." default="usage"&gt;
03. &lt;property name="webroot.dir" value="E:/workspace3/CXFSpring" /&gt;
04. &lt;!-- webservice接口 --&gt;
05. &lt;property name="target.class" value="com.itdcl.service.IService" /&gt;
06. &lt;property name="wsdl.name" value="Service.wsdl" /&gt;
07. &lt;property name="src.dir" value="src" /&gt;
08. &lt;property name="client.dir" value="client" /&gt;
09. &lt;property name="server.dir" value="server" /&gt;
10. &lt;property name="compile.dir" value="${webroot.dir}/bin" /&gt;
11. &lt;target name="usage"&gt;
12. &lt;echo
13. message="java2wsdl         --&gt;java文件生成wsdl文件，java2wsdl -Ddir=com/starit/cxf/java2wsdl -Dsrc=com.starit.cxf.java2wsdl.Hello" /&gt;
14. &lt;echo
15. message="wsdl2javaClient       --&gt;java文件生成client，java2wsdl -Ddir=com/starit/cxf/java2wsdl -Dwsdl=hello.wsdl" /&gt;
16. &lt;/target&gt;
17. &lt;target name="java2wsdl"&gt;
18. &lt;echo message="生成wsdl文件" /&gt;
19. &lt;exec dir="${compile.dir}" executable="cmd.exe"&gt;
20. &lt;arg line="/c java2ws" /&gt;
21. &lt;arg line="-o ${wsdl.name} -wsdl ${target.class}" /&gt;
22. &lt;/exec&gt;
23. &lt;!-- copy资源文件 --&gt;
24. &lt;move todir="${src.dir}" preservelastmodified="true"&gt;
25. &lt;fileset dir="${compile.dir}"&gt;
26. &lt;include name="\*\*/\*.wsdl" /&gt;
27. &lt;/fileset&gt;
28. &lt;/move&gt;
29. &lt;/target&gt;
30. &lt;target name="wsdl2javaClient"&gt;
31. &lt;echo message="生成java client文件" /&gt;
32. &lt;mkdir dir="${client.dir}" /&gt;
33. &lt;exec dir="." executable="cmd.exe"&gt;
34. &lt;arg line="/c wsdl2java" /&gt;
35. &lt;!-- 生成的java所存目录 --&gt;
36. &lt;arg line="-d ${client.dir}"/&gt;
37. &lt;!-- wsdl文件所在路径 --&gt;
38. &lt;arg line="-client src\\\*.wsdl" /&gt;
39. &lt;/exec&gt;
40. &lt;/target&gt;
41. &lt;/project&gt;

    第二步：WebService接口注册配置 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:jaxws="http://cxf.apache.org/jaxws"
05. xsi:schemaLocation="
06. http://www.springframework.org/schema/beans
07. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
08. http://cxf.apache.org/jaxws
09. http://cxf.apache.org/schemas/jaxws.xsd"&gt;
10. &lt;!--  jaxws:client id="helloWorldClient"
11. address="http://localhost:9999/cxf/HelloWorld"
12. serviceClass="com.itdcl.service.IHelloWorld" /&gt;--&gt;
13. &lt;!--  jaxws:client id="myTestClient"
14. address="http://localhost:9999/cxf/MyTest"
15. serviceClass="com.itdcl.service.IMyTest" /&gt;--&gt;
16. &lt;jaxws:client id="service"
17. address="http://localhost:9999/cxf/Service"
18. serviceClass="com.itdcl.service.IService" /&gt;
19. &lt;/beans&gt;

       
    剩下的事就测试我们整合是否成功了，编写一个JUnit测试类或写一个Main函数测试一下。 

Java代码  [![收藏代码](http://xuzhfa123.iteye.com/images/icon_star.png)]()

01. public class JaxbSampleClient {
02. private final static String MODEL = "com.itdcl.model";
03. public static void main(String\[] args) throws FileNotFoundException, JAXBException, ParserConfigurationException, TransformerException {
04. ApplicationContext context = new ClassPathXmlApplicationContext(
05. "beans.xml");
06. IService service = (IService) context.getBean("service");
07. ObjectFactory factory = new ObjectFactory();
08. Customer customer = factory.createCustomer();
09. customer.setId(1);
10. customer.setAge("26");
11. customer.setName("Josen");
12. customer.setAddress(100);
13. Customers customers = factory.createCustomers();
14. customers.setCustomer(customer);
15. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
16. dbf.setNamespaceAware(true);
17. DocumentBuilder db = dbf.newDocumentBuilder();
18. Document doc = db.newDocument();
19. // 转换
20. JAXBContext jaxbContext = JAXBContext.newInstance(MODEL);
21. Marshaller marshaller = jaxbContext.createMarshaller();
22. //将customers数据与doc绑定
23. marshaller.marshal(customers, doc);
24. DOMSource domSource = new DOMSource(doc);
25. StringWriter writer = new StringWriter();
26. StreamResult result = new StreamResult(writer);
27. TransformerFactory tf = TransformerFactory.newInstance();
28. Transformer transformer = tf.newTransformer();
29. transformer.transform(domSource, result);
30. String xmlString = writer.toString();
31. //System.out.println(xmlString);
32. service.update(xmlString);
33. }
34. }