用于Spring JPA2后端的REST CXF

在本演示中,我们将使用spring / jpa2后端生成一个REST / CXF应用程序。

该演示演示了分钟项目的轨迹REST-CXF 。

演示2中的模型保持不变。

浓缩保持不变。

但是轨道改变了

添加的是2层:

  • 在JPA2之上具有弹簧集成的DAO层
  • 具有JAX-RS批注的REST-CXF层

JPA2实体由JAXB注释注释。

所有这些都是为了在模型实体的顶部提供CRUD接口。

组态

这是配置TRANXY-JPA2-Spring-REST-CXF.xml

<!DOCTYPE root>
<generator-config xmlns="http://minuteproject.sf.net/xsd/mp-config" 
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" 
xs:noNamespaceSchemaLocation="../config/mp-config.xsd"><configuration><conventions><target-convention type="enable-updatable-code-feature" /></conventions><model name="tranxy" version="1.0" package-root="net.sf.mp.demo"><data-model><driver name="mysql" version="5.1.16" groupId="mysql"artifactId="mysql-connector-java"></driver><dataSource><driverClassName>org.gjt.mm.mysql.Driver</driverClassName><url>jdbc:mysql://127.0.0.1:3306/tranxy</url><username>root</username><password>mysql</password></dataSource><primaryKeyPolicy oneGlobal="false" ><primaryKeyPolicyPattern name="autoincrementPattern"></primaryKeyPolicyPattern></primaryKeyPolicy></data-model><business-model><generation-condition><condition type="exclude" startsWith="QUARTZ"></condition></generation-condition><business-package default="tranxy"><condition type="package" startsWith="trans" result="translation"></condition></business-package><enrichment><conventions><!-- manipulate the structure and entities BEFORE manipulating the entities --><column-naming-convention type="apply-strip-column-name-suffix"pattern-to-strip="ID" /><reference-naming-conventiontype="apply-referenced-alias-when-no-ambiguity" is-to-plurialize="true" /></conventions><entity name="language_x_translator"><field name="language_id" linkReferenceAlias="translating_language" /><field name="user_id" linkReferenceAlias="translator" /></entity><entity name="LANGUAGE_X_SPEAKER"><field name="LANGUAGE_ID" linkToTargetEntity="LANGUAGE"linkToTargetField="IDLANGUAGE" linkReferenceAlias="spoken_language" /><field name="user_id" linkReferenceAlias="speaker" /></entity><entity name="APPLICATION"><field name="TYPE"><property tag="checkconstraint" alias="application_type"><property name="OPENSOURCE"/><property name="COPYRIGHT" /></property></field></entity></enrichment></business-model></model><targets><target refname="REST-CXF-BSLA" name="default" fileName="mp-template-config-REST-CXF-Spring.xml" outputdir-root="../../DEV/latvianjug/tranxy/rest"templatedir-root="../../template/framework/cxf"></target><target refname="BackendOnBsla" name="default" fileName="mp-template-config-JPA2-bsla.xml" outputdir-root="../../DEV/latvianjug/tranxy/bsla"templatedir-root="../../template/framework/bsla"><property name="add-cache-implementation" value="ehcache"></property></target> <target refname="JPA2" fileName="mp-template-config-JPA2.xml"outputdir-root="../../DEV/latvianjug/tranxy/jpa" templatedir-root="../../template/framework/jpa"><property name="add-querydsl" value="2.1.2"></property><property name="add-jpa2-implementation" value="hibernate"></property><property name="add-cache-implementation" value="ehcache"></property><property name="add-domain-specific-method" value="true"></property><property name="add-xmlbinding" value="true"></property> <property name="add-xml-format" value="lowercase-hyphen"></property> </target><target refname="MavenMaster" name="maven" fileName="mp-template-config-maven.xml" outputdir-root="../../DEV/latvianjug/tranxy"templatedir-root="../../template/framework/maven"></target><target refname="CACHE-LIB" fileName="mp-template-config-CACHE-LIB.xml"templatedir-root="../../template/framework/cache"></target><target refname="LIB" fileName="mp-template-config-bsla-LIB-features.xml"templatedir-root="../../template/framework/bsla">
</target><target refname="REST-LIB" fileName="mp-template-config-REST-LIB.xml" templatedir-root="../../template/framework/rest"></target><target refname="SPRING-LIB" fileName="mp-template-config-SPRING-LIB.xml" templatedir-root="../../template/framework/spring"></target></targets></configuration>
</generator-config>

待办事项说明

在/ mywork / config中设置TRANXY-JPA2-Spring-REST-CXF.xml

> model-generation.cmd TRANXY-JPA2-Spring-REST-CXF.xml 输出进入/ dev / latvianjug / tranxy

产生的伪像

具有3个模块的Maven项目结构

  • JPA2层
  • Spring DAO层
  • CXF层

在演示1和演示2中已经访问了JPA2层。

Spring DAO层

它由每个实体一个的交易服务组成

JPA2之上的CRUD DAO层:该层称为BSLA(基本Spring层体系结构)。

每个实体都会生成两个接口和实现
翻译实体示例

DAO接口

/*** Copyright (c) minuteproject, minuteproject@gmail.com* All rights reserved.* * Licensed under the Apache License, Version 2.0 (the "License")* you may not use this file except in compliance with the License.* You may obtain a copy of the License at* * http://www.apache.org/licenses/LICENSE-2.0* * Unless required by applicable law or agreed to in writing, software* distributed under the License is 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.* * More information on minuteproject:* twitter @minuteproject* wiki http://minuteproject.wikispaces.com * blog http://minuteproject.blogspot.net* 
*/
/*** template reference : * - name : BslaDaoInterfaceUML* - file name : BslaDaoInterfaceUML.vm
*/
package net.sf.mp.demo.tranxy.dao.face.translation;import net.sf.mp.demo.tranxy.domain.translation.Translation;
import java.util.List;
import net.sf.minuteProject.architecture.bsla.bean.criteria.PaginationCriteria;
import net.sf.minuteProject.architecture.bsla.dao.face.DataAccessObject;/**** <p>Title: TranslationDao</p>** <p>Description: Interface of a Data access object dealing with TranslationDao* persistence. It offers a set of methods which allow for saving,* deleting and searching translation objects</p>**/
public interface TranslationDao extends DataAccessObject {/*** Inserts a Translation entity * @param Translation translation*/public void insertTranslation(Translation translation) ;/*** Inserts a list of Translation entity * @param List<Translation> translations*/public void insertTranslations(List<Translation> translations) ;/*** Updates a Translation entity * @param Translation translation*/public Translation updateTranslation(Translation translation) ;/*** Updates a Translation entity with only the attributes set into Translation.* The primary keys are to be set for this method to operate.* This is a performance friendly feature, which remove the udibiquous full load and full update when an* update is to be done* Remark: The primary keys cannot be update by this methods, nor are the attributes that must be set to null.* @param Translation translation*/public int updateNotNullOnlyTranslation(Translation translation) ;public int updateNotNullOnlyPrototypeTranslation(Translation translation, Translation prototypeCriteria);/*** Saves a Translation entity * @param Translation translation*/public void saveTranslation(Translation translation);/*** Deletes a Translation entity * @param Translation translation*/public void deleteTranslation(Translation translation) ;/*** Loads the Translation entity which is related to an instance of* Translation* @param Long id* @return Translation The Translation entitypublic Translation loadTranslation(Long id);
*//*** Loads the Translation entity which is related to an instance of* Translation* @param java.lang.Long Id* @return Translation The Translation entity*/public Translation loadTranslation(java.lang.Long id);    /*** Loads a list of Translation entity * @param List<java.lang.Long> ids* @return List<Translation> The Translation entity*/public List<Translation> loadTranslationListByTranslation (List<Translation> translations);/*** Loads a list of Translation entity * @param List<java.lang.Long> ids* @return List<Translation> The Translation entity*/public List<Translation> loadTranslationListById(List<java.lang.Long> ids);/*** Loads the Translation entity which is related to an instance of* Translation and its dependent one to many objects* @param Long id* @return Translation The Translation entity*/public Translation loadFullFirstLevelTranslation(java.lang.Long id);/*** Loads the Translation entity which is related to an instance of* Translation* @param Translation translation* @return Translation The Translation entity*/public Translation loadFullFirstLevelTranslation(Translation translation);    /*** Loads the Translation entity which is related to an instance of* Translation and its dependent objects one to many* @param Long id* @return Translation The Translation entity*/public Translation loadFullTranslation(Long id) ;/*** Searches a list of Translation entity based on a Translation containing Translation matching criteria* @param Translation translation* @return List<Translation>*/public List<Translation> searchPrototypeTranslation(Translation translation) ;/*** Searches a list of Translation entity based on a list of Translation containing Translation matching criteria* @param List<Translation> translations* @return List<Translation>*/public List<Translation> searchPrototypeTranslation(List<Translation> translations) ;    /*** Searches a list of Translation entity * @param Translation translation* @return List*/public List<Translation> searchPrototypeTranslation(Translation translationPositive, Translation translationNegative) ;/*** Load a paginated list of Translation entity dependent of pagination criteria* @param PaginationCriteria paginationCriteria* @return List*/public List<Translation> loadPaginatedTranslation (Translation translation, PaginationCriteria paginationCriteria) ;}
/*** Copyright (c) minuteproject, minuteproject@gmail.com* All rights reserved.* * Licensed under the Apache License, Version 2.0 (the "License")* you may not use this file except in compliance with the License.* You may obtain a copy of the License at* * http://www.apache.org/licenses/LICENSE-2.0* * Unless required by applicable law or agreed to in writing, software* distributed under the License is 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.* * More information on minuteproject:* twitter @minuteproject* wiki http://minuteproject.wikispaces.com * blog http://minuteproject.blogspot.net* 
*/
/*** template reference : * - name : BslaDaoInterfaceExtendedUML* - file name : BslaDaoInterfaceKFUML.vm
*/
package net.sf.mp.demo.tranxy.dao.face.translation;import net.sf.mp.demo.tranxy.domain.translation.Translation;
import java.util.List;
import net.sf.minuteProject.architecture.filter.data.Criteria;
import net.sf.minuteProject.architecture.bsla.dao.face.DataAccessObject;/**** <p>Title: TranslationExtDao</p>** <p>Description: Interface of a Data access object dealing with TranslationExtDao* persistence. It offers extended DAO functionalities</p>**/
public interface TranslationExtDao extends DataAccessObject {/*** Inserts a Translation entity with cascade of its children* @param Translation translation*/public void insertTranslationWithCascade(Translation translation) ;/*** Inserts a list of Translation entity with cascade of its children* @param List<Translation> translations*/public void insertTranslationsWithCascade(List<Translation> translations) ;        /*** lookup Translation entity Translation, criteria and max result number*/public List<Translation> lookupTranslation(Translation translation, Criteria criteria, Integer numberOfResult);public Integer updateNotNullOnlyTranslation (Translation translation, Criteria criteria);/*** Affect the first translation retrieved corresponding to the translation criteria.* Blank criteria are mapped to null.* If no criteria is found, null is returned.*/public Translation affectTranslation (Translation translation);public Translation affectTranslationUseCache (Translation translation);/*** Assign the first translation retrieved corresponding to the translation criteria.* Blank criteria are mapped to null.* If no criteria is found, null is returned.* If there is no translation corresponding in the database. Then translation is inserted and returned with its primary key(s). */public Translation assignTranslation (Translation translation);/*** Assign the first translation retrieved corresponding to the mask criteria.* Blank criteria are mapped to null.* If no criteria is found, null is returned.* If there is no translation corresponding in the database. * Then translation is inserted and returned with its primary key(s). * Mask servers usually to set unique keys or the semantic reference*/public Translation assignTranslation (Translation translation, Translation mask);public Translation assignTranslationUseCache (Translation translation);/*** return the first Translation entity found*/           public Translation getFirstTranslation (Translation translation);/*** checks if the Translation entity exists*/           public boolean existsTranslation (Translation translation);    public boolean existsTranslationWhereConditionsAre (Translation translation);/*** partial load enables to specify the fields you want to load explicitly*/            public List<Translation> partialLoadTranslation(Translation translation, Translation positiveTranslation, Translation negativeTranslation);/*** partial load with parent entities* variation (list, first, distinct decorator)* variation2 (with cache)*/public List<Translation> partialLoadWithParentTranslation(Translation translation, Translation positiveTranslation, Translation negativeTranslation);public List<Translation> partialLoadWithParentTranslationUseCache(Translation translation, Translation positiveTranslation, Translation negativeTranslation, Boolean useCache);public List<Translation> partialLoadWithParentTranslationUseCacheOnResult(Translation translation, Translation positiveTranslation, Translation negativeTranslation, Boolean useCache);/*** variation first*/public Translation partialLoadWithParentFirstTranslation(Translation translationWhat, Translation positiveTranslation, Translation negativeTranslation);public Translation partialLoadWithParentFirstTranslationUseCache(Translation translationWhat, Translation positiveTranslation, Translation negativeTranslation, Boolean useCache);public Translation partialLoadWithParentFirstTranslationUseCacheOnResult(Translation translationWhat, Translation positiveTranslation, Translation negativeTranslation, Boolean useCache);/*** variation distinct*/public List<Translation> getDistinctTranslation(Translation translationWhat, Translation positiveTranslation, Translation negativeTranslation);//public List partialLoadWithParentForBean(Object bean, Translation translation, Translation positiveTranslation, Translation negativeTranslation);/*** search on prototype with cache*/public List<Translation> searchPrototypeWithCacheTranslation (Translation translation);/*** Searches a list of distinct Translation entity based on a Translation mask and a list of Translation containing Translation matching criteria* @param Translation translation* @param List<Translation> translations* @return List<Translation>*/public List<Translation> searchDistinctPrototypeTranslation(Translation translationMask, List<Translation> translations) ;    public List<Translation> countDistinct (Translation whatMask, Translation whereEqCriteria);public Long count (Translation whereEqCriteria);public List<Translation> loadGraph(Translation graphMaskWhat, List<Translation> whereMask);  public List<Translation> loadGraphFromParentKey (Translation graphMaskWhat, List<Translation> parents); /*** generic to move after in superclass*/public List<Object[]> getSQLQueryResult(String query);     }

DAO实施

TranslationJPAImpl和TranslationJPAExtImpl(未复制代码)。

将来,通用​​DAO将用于跨实体冗余方面。
将执行对spring 3.x的适应(即,不再通过EntityManager注入进行JPASupport扩展)
同时,上面的代码在spring 2.5+上可以正常工作

弹簧配置

spring-config-Tranxy-BE-main.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans><!-- Dao JPA --><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/spring-config-JPA-Tranxy-dao.xml"/>    <!--MP-MANAGED-UPDATABLE-BEGINNING-DISABLE @JPAtranxyFactory-tranxy@--><!-- hibernate config to put in an appart config file--><bean id="JPAtranxyFactory" autowire="byName"class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><!-- all connection information are retrieve from the persistence file--><!--<property name="dataSource" ref="..."/><property name="persistenceUnitName" value="..."/>--><property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /></bean>
<!--MP-MANAGED-UPDATABLE-ENDING--><!-- Database --><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/spring-config-Tranxy-database.xml"/>    </beans>

spring-config-Tranxy-database.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:jndi="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"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.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><bean id="placeHolderConfig"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>classpath:net/sf/mp/demo/tranxy/factory/spring/spring-config-Tranxy.properties</value></property></bean>     <bean id="tranxyTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="JPAtranxyFactory"/></bean><!-- to get the entity manager --><tx:annotation-driven transaction-manager="tranxyTransactionManager"/></beans>

spring-config-Tranxy-BE-main

jdbc.tranxy.driverClassName=org.gjt.mm.mysql.Driver
jdbc.tranxy.url=jdbc:mysql://127.0.0.1:3306/tranxy
jdbc.tranxy.username=root
jdbc.tranxy.password=mysql
jdbc.tranxy.jndi=jdbc/tranxy
hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring-config-JPA-Tranxy-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans><!-- Import Dao definitions for business components --><!-- tranxy --><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/tranxy/dao-JPA-Tranxy.xml"/><!-- translation --><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/translation/dao-JPA-Translation.xml"/><!-- Import Ext Dao definitions for business components --><!-- tranxy extended dao --><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/tranxy/dao-ext-JPA-Tranxy.xml"/><!-- translation extended dao --><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/translation/dao-ext-JPA-Translation.xml"/></beans>

dao-JPA-Translation.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans><bean id="translationDao" class="net.sf.mp.demo.tranxy.dao.impl.jpa.translation.TranslationJPAImpl" singleton="false" ><property name="entityManagerFactory"><ref bean="JPAtranxyFactory"/></property></bean><bean id="translationKeyDao" class="net.sf.mp.demo.tranxy.dao.impl.jpa.translation.TranslationKeyJPAImpl" singleton="false" ><property name="entityManagerFactory"><ref bean="JPAtranxyFactory"/></property></bean><bean id="translationRequestDao" class="net.sf.mp.demo.tranxy.dao.impl.jpa.translation.TranslationRequestJPAImpl" singleton="false" ><property name="entityManagerFactory"><ref bean="JPAtranxyFactory"/></property></bean></beans>

dao-ext-JPA-Translation.xml,dao-ext-JPA-Tranxy.xml,dao-JPA-Tranxy.xml文件相同

但是请稍等...如何进行单元测试?

在编写自己的测试之前,您还需要另外两个工件。

一个是persistence.xml

再次? 是的,对于嵌入式连接池,因为JPA2层的构建随附提供的引用可能是JNDI数据源(如果将属性环境设置为远程)。
由于它位于/ src / test / resources / META-INF下,因此它将覆盖JPA2软件包中的那个。

二是扩展AbstractTransactionalJUnit4SpringContextTests 的适配器 :它在/ src / test / java中生成

package net.sf.mp.demo.tranxy.dao.face;import javax.sql.DataSource;import org.apache.commons.lang.StringUtils;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:net/sf/mp/demo/tranxy/factory/spring/spring-config-Tranxy-BE-main.xml"
})
@TransactionConfiguration(transactionManager = "tranxyTransactionManager") 
@Transactional
public class AdapterTranxyTestDao extends AbstractTransactionalJUnit4SpringContextTests { @Override@Autowiredpublic void setDataSource(@Qualifier(value = "tranxyDataSource") DataSource dataSource) {this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);}
...

CXF

每个实体都有一个带有JAX-RS批注的Rest Resource工件,以启用CRUD访问。 翻译示例

/*** Copyright (c) minuteproject, minuteproject@gmail.com* All rights reserved.* * Licensed under the Apache License, Version 2.0 (the "License")* you may not use this file except in compliance with the License.* You may obtain a copy of the License at* * http://www.apache.org/licenses/LICENSE-2.0* * Unless required by applicable law or agreed to in writing, software* distributed under the License is 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.* * More information on minuteproject:* twitter @minuteproject* wiki http://minuteproject.wikispaces.com * blog http://minuteproject.blogspot.net* 
*/
/*** template reference : * - name : CXFSpringEntityResource* - file name : CXFSpringEntityResource.vm
*/
package net.sf.mp.demo.tranxy.rest.translation;import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.sql.*;import javax.servlet.http.*;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;import net.sf.mp.demo.tranxy.dao.face.translation.TranslationDao;
import net.sf.mp.demo.tranxy.dao.face.translation.TranslationExtDao;
import net.sf.mp.demo.tranxy.domain.translation.Translation;/**** <p>Title: TranslationResource</p>** <p>Description: remote interface for TranslationResource service </p>**/
@Path ("/rest/xml/translations")
@Produces ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Service
@Transactional
public class TranslationResource  {@Autowired@Qualifier("translationDao")TranslationDao translationDao;@Autowired@Qualifier("translationExtDao")TranslationExtDao translationExtDao;//MP-MANAGED-UPDATABLE-BEGINNING-DISABLE @FIND_ALL-translation@@GET@Produces ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public List<Translation> findAll () {List<Translation> r = new ArrayList<Translation>();List<Translation> l = translationDao.searchPrototypeTranslation(new Translation());for (Translation translation : l) {r.add(translation.flat());}return r;}
//MP-MANAGED-UPDATABLE-ENDING//MP-MANAGED-UPDATABLE-BEGINNING-DISABLE @FIND_BY_ID-translation@@GET@Path("{id}")@Produces ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  public Translation findById (@PathParam ("id") java.lang.Long id) {Translation _translation = new Translation ();_translation.setId(id);_translation = translationExtDao.getFirstTranslation(_translation);if (_translation!=null) return _translation.flat();return new Translation ();}
//MP-MANAGED-UPDATABLE-ENDING@DELETE@Path("{id}")public void delete (@PathParam ("id") Long id) {Translation translation = new Translation ();translation.setId(id);translationDao.deleteTranslation(translation);}@POST@Produces ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Translation create (@FormParam("id") Long id,@FormParam("translation") String translation,@FormParam("language") Integer language,@FormParam("key") Long key,@FormParam("isFinal") Short isFinal,@FormParam("dateFinalization") Date dateFinalization,@FormParam("translator") Long translator,@Context HttpServletResponse servletResponse) throws IOException {Translation _translation = new Translation (id,translation,language,key,isFinal,dateFinalization,translator);return save(_translation);}@PUT@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Translation save(JAXBElement<Translation> jaxbTranslation) {Translation translation = jaxbTranslation.getValue();if (translation.getId()!=null)return translationDao.updateTranslation(translation);return save(translation);}public Translation save (Translation translation) {translationDao.saveTranslation(translation);return translation;}}

Web应用程序和Spring的两个文件位于/ src / main / resources / webapp / WEB-INF

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"><display-name>tranxy CXF REST</display-name><description>tranxy CXF REST access</description><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/application-context.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet><servlet-name>CXFServlet</servlet-name><servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>CXFServlet</servlet-name><url-pattern>/*</url-pattern></servlet-mapping></web-app>

application-context.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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jaxrs="http://cxf.apache.org/jaxrs"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd"><import resource="classpath:META-INF/cxf/cxf.xml" /><import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" /><import resource="classpath:META-INF/cxf/cxf-servlet.xml" /><context:component-scan base-package="net.sf.mp.demo.tranxy.rest"/><import resource="classpath:net/sf/mp/demo/tranxy/factory/spring/spring-config-Tranxy-BE-main.xml"/>    <jaxrs:server id="restContainer" address="/"><jaxrs:serviceBeans><!-- tranxy --> <ref bean="applicationResource"/><ref bean="languageResource"/><ref bean="userResource"/><!-- translation --> <ref bean="translationResource"/><ref bean="translationKeyResource"/><ref bean="translationRequestResource"/><!-- statements --></jaxrs:serviceBeans></jaxrs:server> </beans>

打包,部署和测试


在生成软件包之前,minuteproject mp-bsla.xyjar附带了一个依赖项以进行安装。 在/ target / mp-bsla /运行脚本中:maven-install.cmd / sh 构建:> MVN清洁包

结果是/ rest / target中的tranxyRestCxfApp.war

部署方式
启动tomcat
将tranxyRestCxfApp.war放到/ webapps中 有一个嵌入式连接池,因此不需要在tomcat上进行任何配置。

测试

USE `tranxy` ;
DELETE FROM application_x_key;
DELETE FROM translation;
DELETE FROM language_x_translator;
DELETE FROM language_x_speaker;
DELETE FROM request_key;DELETE FROM application;
DELETE FROM translation_key;
DELETE FROM user;
DELETE FROM language;INSERT INTO application (idapplication,  name, description, type) VALUES (-1,'Porphyry', 'OS application holding environment app', 'OPENSOURCE');
INSERT INTO application (idapplication,  name, description, type) VALUES (-2,'Minuteproject', 'Minuteproject app', 'OPENSOURCE');INSERT INTO user (iduser, first_name, last_name, email) VALUES (-1,'test', 'lastName', 'test@test.me');
INSERT INTO user (iduser, first_name, last_name, email) VALUES (-2,'test2', 'lastName2', 'test2@test.me');INSERT INTO language (idlanguage, code, description, locale) VALUES (-1, 'FR', 'France', 'fr');
INSERT INTO language (idlanguage, code, description, locale) VALUES (-2, 'ES', 'Spanish', 'es');                                                                                               
INSERT INTO language (idlanguage, code, description, locale) VALUES (-3, 'EN', 'English', 'en');          INSERT INTO language_x_translator (language_id, user_id) VALUES (-1, -1);
INSERT INTO language_x_translator (language_id, user_id) VALUES (-2, -1);
INSERT INTO language_x_speaker (language_id, user_id) VALUES (-1, -1);
INSERT INTO language_x_speaker (language_id, user_id) VALUES (-2, -1);INSERT INTO language_x_translator (language_id, user_id) VALUES (-1, -2);
INSERT INTO language_x_translator (language_id, user_id) VALUES (-2, -2);
INSERT INTO language_x_translator (language_id, user_id) VALUES (-3, -2);    INSERT INTO translation_key (id, key_name, description) VALUES (-1, 'msg.user.name', 'user name');
INSERT INTO translation (id, translation, language_id, key_id, is_final, date_finalization, translator_id) 
VALUES (-1, 'nom', -1, -1, 1, '2012-04-04', -1);
INSERT INTO translation (id, translation, language_id, key_id, is_final, date_finalization, translator_id) 
VALUES (-2, 'apellido', -1, -2, 1, CURDATE(), -1);

现在输入
http:// localhost:8080 / tranxyRestCxfApp / rest / xml / languages以获取所有语言

这是结果

现在输入
http:// localhost:8080 / tranxyRestCxfApp / rest / xml / users / -1获取第一个用户

这是结果

结论

本文介绍了如何在数据库模型之上快速获取CRUD REST接口。 当然,您可能不需要对所有实体都使用CRUD,并且可能需要更多的粗粒度函数来操纵模型。 下一篇文章将向您展示语句驱动开发如何使我们更接近用例。

参考: RigaJUG –演示–来自JCG合作伙伴 Florian Adler的REST CXF ,位于minuteproject博客博客上。


翻译自: https://www.javacodegeeks.com/2012/05/rest-cxf-for-spring-jpa2-backend.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/372659.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

完整的WebApplication JSF EJB JPA JAAS –第1部分

这篇文章将是迄今为止我博客中最大的一篇文章&#xff01; 我们将看到完整的Web应用程序。 最新的技术将完成此工作&#xff08;直到今天&#xff09;&#xff0c;但是我将给出一些提示以显示如何使本文适用于较旧的技术。 在本文的结尾&#xff0c;您将找到要下载的源代码。 您…

使用Hibernate加载或保存图像-MySQL

本教程将引导您逐步了解如何使用Hibernate从数据库&#xff08; MySQL &#xff09;保存和加载图像。 要求 对于此示例项目&#xff0c;我们将使用&#xff1a; Eclipse IDE &#xff08;您可以使用自己喜欢的IDE&#xff09;&#xff1b; MySQL &#xff08;您可以使用任何…

javaweb回顾第四篇Servlet异常处理

前言&#xff1a;很多网站为了给用户很好的用户体验性&#xff0c;都会提供比较友好的异常界面&#xff0c;现在我们在来回顾一下Servlet中如何进行异常处理的。 1&#xff1a;声明式异常处理 什么是声明式&#xff1a;就是在web.xml中声明对各种异常的处理方法。 是通过<er…

java开发cs教程,日常运维(一)

w命令&#xff1a;用于查看系统负载、显示已经登陆系统的用户列表&#xff0c;并显示用户正在执行的指令等信息第一行从左面开始显示的信息依次为&#xff1a;时间&#xff0c;系统运行时间&#xff0c;登录用户数&#xff0c;平均负载。第二行开始以及下面所有的行&#xff0c…

coursera 《现代操作系统》 -- 第五周 同步机制(1)

临界区块&#xff08;Critical section&#xff09;指的是一个访问共用资源&#xff08;例如&#xff1a;共用设备或是共用存储器&#xff09;的程序片段&#xff0c;而这些共用资源有无法同时被多个线程访问的特性。&#xff08;不是字面意思的一个区域&#xff0c;是程序片段…

php进度条插件,分享8款优秀的 jQuery 加载动画和进度条插件_jquery

加载动画和进度条在网站和 Web 应用中的使用非常流行。虽然网速越来越快&#xff0c;但是我们的网站越来越复杂&#xff0c;同时用户对网站的使用体验的要求也越来越高。在内容加载缓慢的时候&#xff0c;使用时尚的加载动画和进度条告诉用户还有内容正在加载是一种非常好的方式…

卷积神经网络(CNN)与特殊的卷积

各种卷积操作的可视化的显示形式&#xff1a;GitHub - vdumoulin/conv_arithmetic: A technical report on convolution arithmetic in the context of deep learning1. fractionally-strided 卷积 如上图示&#xff0c;输入为 33 &#xff0c;想要卷积上采样成 55 的输出。需要…

MySQL安装步骤及相关问题解决

1. 下载MySQL Server&#xff0c;网址&#xff1a;http://dev.mysql.com/downloads/mysql/ 2. 点击MySQL5.5.21的安装文件&#xff0c;出现安装向导界面&#xff0c;单击“next”继续安装&#xff1a; 3. 选择接受协议&#xff0c;单击“next”继续安装&#xff1a; 4. 在出现选…

matlab的数学函数,matlab中常见数学函数的使用

matlab中常见数学函数的使用 MATLAB 基本知识 Matlab 的内部常数 pi 圆周率 exp(1) 自然对数的底数 e i 或 j 虚数单位 Inf 或 inf 无穷大 Matlab 的常用内部数学函数 指数函数 exp(x) 以 e 为底数 log(x) 自然对数&#xff0c;即以 e 为底数的对数 log10(x) 常用对数&#xff…

C++中 list与vector的区别

C中 list与vector的区别 引用http://www.cnblogs.com/shijingjing07/p/5587719.html C vector和list的区别 1.vector数据结构vector和数组类似&#xff0c;拥有一段连续的内存空间&#xff0c;并且起始地址不变。因此能高效的进行随机存取&#xff0c;时间复杂度为o(1);但因为内…

ActiveMQ网络连接器

这篇文章对我和任何对网络连接器如何为ActiveMQ工作感兴趣的ActiveMQ贡献者而言都是更多的内容。 我最近花了一些时间查看代码&#xff0c;并认为最好画一些快速的图表来帮助我记住我学到的东西&#xff0c;并在将来发现问题时帮助将来确定在哪里进行调试。 如果我输入有误&…

《程序设计与数据结构》第3周学习总结

学号 20162317 《程序设计与数据结构》第3周学习总结 教材学习内容总结 第三章的内容相比之前两章更为具体&#xff0c;介绍的内容更为集中&#xff0c;主要说到了类和对象的问题&#xff0c;其中也仔细介绍了String类、Random类、Math类、NumberFormat类等类。此外也说到了与类…

Java中带有JWebSocket的WebServerSocket

首先&#xff0c;转到http://jwebsocket.org/下载2个软件包Server and Client。 如果要查看源代码&#xff0c;请下载源代码包。 服务器 解压缩服务器程序包。 转到“ conf”文件夹 选择“ jWebSocket.xml”文件打开 编辑“ jWebSocket.xml”文件&#xff0c;在标签<dom…

OpenCV入门指南----人脸检测

本篇介绍图像处理与模式识别中最热门的一个领域——人脸检测&#xff08;人脸识别&#xff09;。人脸检测可以说是学术界的宠儿&#xff0c;在不少EI&#xff0c;SCI高级别论文都能看到它的身影。甚至很多高校学生的毕业设计都会涉及到人脸检测。当然人脸检测的巨大实用价值也让…

matlab提取艾里斑,艾里斑:我不是雀斑

正是艾里斑&#xff0c;限制了光学仪器的精度我们知道凸透镜能把入射光会聚到它的焦点上&#xff0c;由于透镜的口径有一定大小&#xff0c;限制了光线的传播&#xff0c;所以凸透镜也会发生衍射。这导致透镜无法把光线会聚成无限小的点&#xff0c;而只会在焦点上形成具有一定…

mysql启动错误排查-无法申请足够内存

一般情况下mysql的启动错误还是很容易排查的&#xff0c;但是今天我们就来说一下不一般的情况。拿到一台服务器&#xff0c;安装完mysql后进行启动&#xff0c;启动错误如下&#xff1a; 有同学会说&#xff0c;哥们儿你是不是buffer pool设置太大了&#xff0c;设置了96G内存。…

loadrunner 关联

1、记住关联的位置&#xff08;之前&#xff09;&#xff0c;因为登录之前需要token&#xff0c;才能验证登录是否成功&#xff0c;所以&#xff0c;放在登录之前 转载于:https://www.cnblogs.com/zyp1/p/5692343.html

Akka STM –与STM Ref和Agent进行乒乓球比赛

乒乓是一个经典示例&#xff0c;其中2个玩家&#xff08;或线程&#xff09;访问共享资源–乒乓球桌并在彼此之间传递Ball&#xff08;状态变量&#xff09;。 使用任何共享资源&#xff0c;除非我们同步访问&#xff0c;否则线程可能会遇到潜在的死锁情况。 PingPong算法非常简…

JSP九大内置对象,七大动作,三大指令

JSP之九大内置对象 隐藏对象入门探索 Servlet 和JSP中输出数据都需要使用out对象。Servlet 中的out对象是通过getWriter()方法获取的。而JSP中没有定义out对象却可以直接使用。这是因为out是JSO的内置隐藏对象。JSP中的常见的9个内置隐藏对象如下 out输出流对象 隐藏对象out是…

可以添加自定义的Select控件

1.控件dom <select name"WebSiteTarget" id"WebSiteTarget" class"w1" onchange"editable2(this);"><option value"-1">请选择城市</option><option>福州</option><option>厦门</op…