Cxf+spring+hibernate Implementing a RESTful WebService service-side instance

Source: Internet
Author: User
Tags aop

1.RESTful API Interface Definition

/* * Copyright 2016-2017 witpool.org All rights Reserved. * * Except in compliance with the License. * A copy of the License is located at * http://www.witpool.org/licenses */or in the ' License ' file accompanying this F Ile.  This file was distributed * on an ' as is ' BASIS, without warranties or CONDITIONS of any KIND, either * Express OR implied. See the License for the specific language governing * permissions and limitations under the License. */package org.witpool.rest;import javax.ws.rs.delete;import Javax.ws.rs.get;import javax.ws.rs.POST;import Javax.ws.rs.put;import Javax.ws.rs.path;import Javax.ws.rs.pathparam;import Org.witpool.common.model.bean.witentity;import org.witpool.common.model.po.witaccount;/** * @ClassName: Iwitaccount * @Description: Account service definition * @author Dom Wang * @date 2017-11-11 AM 11:21:55 * @version 1. 0 * * @Path ("/account") public interface iwitaccount{/** * * * @Title: AddAccount * @DescriptiOn:add Account * @param @param account * @param @return * @return witentity<witaccount> * @th    Rows */@POST witentity<witaccount> AddAccount (witaccount account); /** * * * @Title: Updateaccount * @Description: Update account * @param @param account * @param @retu RN * @return witentity<witaccount> * @throws * */@PUT witentity<witaccount> UPDATEACC    Ount (Witaccount account); /** * * * @Title: Delaccount * @Description: Delete account by User ID * @param @param userId * @para M @return * @return witentity<witaccount> * @throws */@DELETE @Path ("/{userid}") WitEn    Tity<witaccount> Delaccount (@PathParam ("userid") Integer userId);  /** * * * @Title: Getaccount * @Description: Query account by User ID * @param @param userId * @param     @return * @return witentity<witaccount> * @throws*/@GET @Path ("/{userid}") Witentity<witaccount> Getaccount (@PathParam ("userid") Integer userId); /** * * * @Title: Getaccount * @Description: Query All the accounts * @param @param userId * @param @ return * @return witentity<witaccount> * @throws * */@GET @Path ("/all") Witentity<wit Account> getaccounts ();}

2.CXF integrated with spring configuration

<?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:jaxrs= "Http://cxf.apache.org/jaxrs" xmlns:cxf= "http// Cxf.apache.org/core "xmlns:util=" Http://www.springframework.org/schema/util "xmlns:p="/HTTP/ www.springframework.org/schema/p "xsi:schemalocation=" Http://www.springframework.org/schema/beans http                      ://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/util Http://www.springframework.org/schema/util/spring-util.xsd Http://cxf.apache.org/ja XRS http://cxf.apache.org/schemas/jaxrs.xsd "> <import resource=" classpath*:meta-inf/cxf/cxf . xml "/> <import resource=" Classpath*:meta-inf/cxf/cxf-servlet.xml "/> <import resource=" Classpath:per     Sist-config.xml "/> <jaxrs:server id=" Witpool "address="/">    <jaxrs:inInterceptors> <bean class= "Org.apache.cxf.interceptor.LoggingInInterceptor"/> </jaxrs:inInterceptors> <jaxrs:outInterceptors> <bean class= "org.apache.cxf.intercept Or. Loggingoutinterceptor "/> </jaxrs:outInterceptors> <jaxrs:providers> <ref be an= "Jacksonprovider"/> </jaxrs:providers> <jaxrs:extensionMappings> <entry key= "JSON" value= "Application/json"/> <entry key= "xml" value= "Application/xml"/> </jaxrs:e xtensionmappings> <jaxrs:serviceBeans> <ref bean= "Witaccount"/> </jaxrs:se rvicebeans> </jaxrs:server> <bean id= "Jaxbannotationintrospector" class= "Com.fasterxml.jackson.module . Jaxb. Jaxbannotationintrospector "/> <bean id=" Jsonmapper "class=" Org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean "p:annotationintrospector-ref=" Jaxbannotationintrospector "> <property name=" featurestoenable "> <array> <util:constant static-field= "com.fasterxml.jackson.databind.serializationfeature.i Ndent_output "/> <util:constant static-field=" Com.fasterxml.jackson.databind.SerializationFeature.WR Ite_dates_as_timestamps "/> </array> </property> <property name=" Featurestod Isable "> <array> <util:constant static-field=" Com.fasterxml.jackson.databind.Seria Lizationfeature.write_null_map_values "/> <util:constant static-field=" Com.fasterxml.jackson.databin D.serializationfeature.write_empty_json_arrays "/> </array> </property> <pro         Perty name= "Objectmapper" > <bean class= "Com.fasterxml.jackson.databind.ObjectMapper" ></bean> </property>   </bean> <bean id= "Jacksonprovider" class= "Com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider" > <property name= "Mapper" ref= "Jsonmapper"/> </bean> <bean id= "Witaccount" class= "ORG.WITPOOL.R Est.impl.WitAccountImpl "/> </beans>

3.Spring integrated configuration with Hibernate

<?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-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.1.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.1.xsd "> <!--Scan Bean--<context:component-scan base-package=" Org.witpoo L.common.model.po "> <context:exclude-filter type=" annotation "expression=" Org.sprinGframework.stereotype.Controller "/> </context:component-scan> <bean id=" Propertyconfigurer "class=" or             G.springframework.beans.factory.config.propertyplaceholderconfigurer "> <property name=" Locations ">         <list> <value>classpath:resources.properties</value> </list> </property> </bean> <bean id= "DataSource" class= "Org.logicalcobwebs.proxool.ProxoolDataSource "> <property name=" Alias "value=" Proxooldatasource "/> <property name=" Driver "value=" ${connec Tion.driver_class} "/> <property name=" Driverurl "value=" ${connection.url} "/> <property name=          "User" value= "${connection.username}"/> <property name= "password" value= "${connection.password}"/> <property name= "Maximumconnectioncount" value= "${proxool.maximum.connection.count}"/> <property name = "Minimumconnectioncount"Value=" ${proxool.minimum.connection.count} "/> <property name=" Statistics "value=" ${proxool.statistics} "/&          Gt <property name= "Simultaneousbuildthrottle" value= "${proxool.simultaneous.build.throttle}"/> </bean> & Lt;bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean" > <property na                 Me= "DataSource" ref= "DataSource"/> <property name= "Packagestoscan" > <list> <value>org.witpool.common.model.po</value> </list> </property> & Lt;property name= "Hibernateproperties" > <props> <prop key= "Hibernate.dialect" >$                  {hibernate.dialect}</prop> <prop key= "Hibernate.show_sql" >${hibernate.show_sql}</prop> <prop key= "Hibernate.format_sql" >true</prop> <prop key= "Hibernate.query.s UbstitutionS ">${hibernate.query.substitutions}</prop> <prop key=" Hibernate.default_batch_fetch_size "> ${hibernate.default_batch_fetch_size}</prop> <prop key= "Hibernate.max_fetch_depth" >${hibernat e.max_fetch_depth}</prop> <prop key= "Hibernate.generate_statistics" >${hibernate.generate_stat istics}</prop> <prop key= "Hibernate.bytecode.use_reflection_optimizer" >${hibernate.bytecode.u se_reflection_optimizer}</prop> <prop key= "Hibernate.hbm2ddl.auto" >${hibernate.bytecode.use_r eflection_optimizer}</prop> <prop key= "Hibernate.hbm2ddl.auto" >${hibernate.hbm2ddl.auto}</ prop> </props> </property> </bean> <tx:annotation-driven transaction- manager= "TransactionManager"/> <bean id= "TransactionManager" class= " Org.springframework.orm.hibernate4.HibernateTransactionManager ">         <property name= "Sessionfactory" ref= "sessionfactory"/> </bean> <aop:config> &L T;aop:pointcut id= "Rest-api" expression= "Execution (* org.witpool.rest.*.* (..))" /> <aop:advisor pointcut-ref= "Rest-api" advice-ref= "Txadvice"/> </aop:config> <tx:advi Ce id= "txadvice" transaction-manager= "TransactionManager" > <tx:attributes> <tx:method Name = "find*" read-only= "false" propagation= "not_supported"/> <tx:method name= "query*" read-only= "false" pro              pagation= "not_supported"/> <tx:method name= "get*" read-only= "false" propagation= "not_supported"/> <tx:method name= "Add" propagation= "REQUIRED"/> <tx:method name= "add*" propagation= "Requir ED "/> <tx:method name=" update* "propagation=" REQUIRED "/> <tx:method name=" Delete "PR opagation= "REQUIRED"/> <tx:method name= "delete*" propagation= "REQUIRED"/> <tx:method name= "save" propagation= "REQUIRED"/> <tx:method Name= "save*" propagation= "REQUIRED"/> <tx:method name= "*" propagation= "REQUIRED"/> </tx:         attributes> </tx:advice> <bean id= "Basedao" class= "Org.witpool.persist.dao.impl.BaseDaoImpl" >     <property name= "Sessionfactory" ref= "sessionfactory"/> <property name= "Basedao" ref= "BaseDao"/> </bean> </beans>

parameter configuration for 4.Hibernate

Hibernate.dialect=org.hibernate.dialect.mysqldialecthibernate.hbm2ddl.auto=updatehibernate.show_sql= Truehibernate.query.substitutions=true 1, False 0hibernate.default_batch_fetch_size=16hibernate.max_fetch_depth= 2hibernate.bytecode.use_reflection_optimizer=truehibernate.cache.use_second_level_cache= truehibernate.cache.use_query_cache=truehibernate.cache.region.factory_class= Org.hibernate.cache.ehcacheregionfactorynet.sf.ehcache.configurationresourcename=/ehcache_ Hibernate.xmlhibernate.cache.use_structured_entries=truehibernate.generate_statistics=trueconnection.driver_ Class=com.mysql.jdbc.driverconnection.url=jdbc:mysql://localhost:3306/witpool?createdatabaseifnotexist=true &useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull& Transformedbitisboolean=trueconnection.username=rootconnection.password=123456proxool.maximum.connection.count =40proxool.minimum.connection.count=5proxool.statistics=1m,15m,1h,1dproxool.simultaneous.build.throttle=30

5. Code download, compile, package

To download the code, visit the Witpool/wit-pluto on GitHub.
Import the project file, compile, and package the following steps:



6. Deployment and UT steps

Copy the compiled-generated package wit-rest.war to Tomcat 8.5\webapps\ , restart Tomcat
UT steps:
(1). Download Wisdomtool REST Client
(2). Double-click the Jar package restclient-1.1.jar startup tool
To import a test case file:

For more help with Wisdomtool REST client, refer to GitHub wisdomtool/rest-client

Cxf+spring+hibernate Implementing a RESTful WebService service-side instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.