first step of migration to Spring 3.2 (still in process)

This commit is contained in:
Mic 2013-01-09 17:24:48 +08:00
parent 5f25d7483d
commit 87ccf9fea1
95 changed files with 507 additions and 1764 deletions

View file

@ -18,7 +18,7 @@ import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.orm.ObjectRetrievalFailureException;
@ -58,7 +58,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
private final Logger logger = LoggerFactory.getLogger(getClass());
private SimpleJdbcTemplate simpleJdbcTemplate;
private JdbcTemplate simpleJdbcTemplate;
private SimpleJdbcInsert insertOwner;
private SimpleJdbcInsert insertPet;
@ -69,7 +69,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
@Autowired
public void init(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.simpleJdbcTemplate = new JdbcTemplate(dataSource);
this.insertOwner = new SimpleJdbcInsert(dataSource)
.withTableName("owners")

View file

@ -1,56 +0,0 @@
package org.springframework.samples.petclinic.toplink;
import java.io.IOException;
import java.io.Writer;
import oracle.toplink.essentials.exceptions.ValidationException;
import oracle.toplink.essentials.platform.database.HSQLPlatform;
import oracle.toplink.essentials.queryframework.ValueReadQuery;
/**
* Subclass of the TopLink Essentials default HSQLPlatform class, using native
* HSQLDB identity columns for id generation.
*
* <p>Necessary for PetClinic's default data model, which relies on identity
* columns: this is uniformly used across all persistence layer implementations
* (JDBC, Hibernate, and JPA).
*
* @author Juergen Hoeller
* @author <a href="mailto:james.x.clark@oracle.com">James Clark</a>
* @since 1.2
*/
public class EssentialsHSQLPlatformWithNativeSequence extends HSQLPlatform {
private static final long serialVersionUID = -55658009691346735L;
public EssentialsHSQLPlatformWithNativeSequence() {
// setUsesNativeSequencing(true);
}
@Override
public boolean supportsNativeSequenceNumbers() {
return true;
}
@Override
public boolean shouldNativeSequenceAcquireValueAfterInsert() {
return true;
}
@Override
public ValueReadQuery buildSelectQueryForNativeSequence() {
return new ValueReadQuery("CALL IDENTITY()");
}
@Override
public void printFieldIdentityClause(Writer writer) throws ValidationException {
try {
writer.write(" IDENTITY");
}
catch (IOException ex) {
throw ValidationException.fileError(ex);
}
}
}

View file

@ -1,10 +0,0 @@
/**
*
* The classes in this package provide support for using the TopLink
* implementation with PetClinic's EntityManagerClinic.
*
*
*/
package org.springframework.samples.petclinic.toplink;

166
src/main/resources/log4j.dtd Executable file
View file

@ -0,0 +1,166 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Authors: Chris Taylor, Ceki Gulcu. -->
<!-- Version: 1.2 -->
<!-- A configuration element consists of optional renderer
elements,appender elements, categories and an optional root
element. -->
<!ELEMENT log4j:configuration (renderer*, appender*,(category|logger)*,root?,
categoryFactory?)>
<!-- The "threshold" attribute takes a level value such that all -->
<!-- logging statements with a level equal or below this value are -->
<!-- disabled. -->
<!-- Setting the "debug" enable the printing of internal log4j logging -->
<!-- statements. -->
<!-- By default, debug attribute is "null", meaning that we not do touch -->
<!-- internal log4j logging settings. The "null" value for the threshold -->
<!-- attribute can be misleading. The threshold field of a repository -->
<!-- cannot be set to null. The "null" value for the threshold attribute -->
<!-- simply means don't touch the threshold field, the threshold field -->
<!-- keeps its old value. -->
<!ATTLIST log4j:configuration
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
threshold (all|debug|info|warn|error|fatal|off|null) "null"
debug (true|false|null) "null"
>
<!-- renderer elements allow the user to customize the conversion of -->
<!-- message objects to String. -->
<!ELEMENT renderer EMPTY>
<!ATTLIST renderer
renderedClass CDATA #REQUIRED
renderingClass CDATA #REQUIRED
>
<!-- Appenders must have a name and a class. -->
<!-- Appenders may contain an error handler, a layout, optional parameters -->
<!-- and filters. They may also reference (or include) other appenders. -->
<!ELEMENT appender (errorHandler?, param*, layout?, filter*, appender-ref*)>
<!ATTLIST appender
name ID #REQUIRED
class CDATA #REQUIRED
>
<!ELEMENT layout (param*)>
<!ATTLIST layout
class CDATA #REQUIRED
>
<!ELEMENT filter (param*)>
<!ATTLIST filter
class CDATA #REQUIRED
>
<!-- ErrorHandlers can be of any class. They can admit any number of -->
<!-- parameters. -->
<!ELEMENT errorHandler (param*, root-ref?, logger-ref*, appender-ref?)>
<!ATTLIST errorHandler
class CDATA #REQUIRED
>
<!ELEMENT root-ref EMPTY>
<!ELEMENT logger-ref EMPTY>
<!ATTLIST logger-ref
ref IDREF #REQUIRED
>
<!ELEMENT param EMPTY>
<!ATTLIST param
name CDATA #REQUIRED
value CDATA #REQUIRED
>
<!-- The priority class is org.apache.log4j.Level by default -->
<!ELEMENT priority (param*)>
<!ATTLIST priority
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!-- The level class is org.apache.log4j.Level by default -->
<!ELEMENT level (param*)>
<!ATTLIST level
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named category. -->
<!ELEMENT category (param*,(priority|level)?,appender-ref*)>
<!ATTLIST category
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
>
<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named logger. -->
<!ELEMENT logger (level?,appender-ref*)>
<!ATTLIST logger
name ID #REQUIRED
additivity (true|false) "true"
>
<!ELEMENT categoryFactory (param*)>
<!ATTLIST categoryFactory
class CDATA #REQUIRED>
<!ELEMENT appender-ref EMPTY>
<!ATTLIST appender-ref
ref IDREF #REQUIRED
>
<!-- If no priority element is specified, then the configurator MUST not -->
<!-- touch the priority of root. -->
<!-- The root category always exists and cannot be subclassed. -->
<!ELEMENT root (param*, (priority|level)?, appender-ref*)>
<!-- ==================================================================== -->
<!-- A logging event -->
<!-- ==================================================================== -->
<!ELEMENT log4j:eventSet (log4j:event*)>
<!ATTLIST log4j:eventSet
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
version (1.1|1.2) "1.2"
includesLocationInfo (true|false) "true"
>
<!ELEMENT log4j:event (log4j:message, log4j:NDC?, log4j:throwable?,
log4j:locationInfo?) >
<!-- The timestamp format is application dependent. -->
<!ATTLIST log4j:event
logger CDATA #REQUIRED
level CDATA #REQUIRED
thread CDATA #REQUIRED
timestamp CDATA #REQUIRED
>
<!ELEMENT log4j:message (#PCDATA)>
<!ELEMENT log4j:NDC (#PCDATA)>
<!ELEMENT log4j:throwable (#PCDATA)>
<!ELEMENT log4j:locationInfo EMPTY>
<!ATTLIST log4j:locationInfo
class CDATA #REQUIRED
method CDATA #REQUIRED
file CDATA #REQUIRED
line CDATA #REQUIRED
>

View file

@ -1,18 +0,0 @@
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${petclinic.root}/WEB-INF/petclinic.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.org.springframework.samples.petclinic.aspects=DEBUG

27
src/main/resources/log4j.xml Executable file
View file

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p: %c - %m%n" />
</layout>
</appender>
<logger name="org.springframework.samples.petclinic.aspects">
<level value="DEBUG" />
</logger>
<!-- Root Logger -->
<root>
<priority value="info" /><!--
<level value="info"></level>
--><appender-ref ref="console" />
</root>
</log4j:configuration>

View file

@ -1,12 +1,10 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<table class="footer">
<tr>
<td><a href="<spring:url value="/" htmlEscape="true" />">Home</a></td>
<td align="right"><img src="<spring:url value="/static/images/springsource-logo.png" htmlEscape="true" />" alt="Sponsored by SpringSource"/></td>
<td align="right"><img src="<spring:url value="/resources/images/springsource-logo.png" htmlEscape="true" />" alt="Sponsored by SpringSource"/></td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -1,7 +1,8 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!--
PetClinic :: a Spring Framework demonstration
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
@ -9,6 +10,4 @@
<title>PetClinic :: a Spring Framework demonstration</title>
</head>
<body>
<div id="main">

View file

@ -1,26 +1,38 @@
<%@ include file="/WEB-INF/jsp/includes.jsp" %>
<%@ include file="/WEB-INF/jsp/header.jsp" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html lang="en">
<h2>Find Owners:</h2>
<jsp:include page="../header.jsp"/>
<spring:url value="/owners" var="formUrl"/>
<form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get">
<table>
<tr>
<th>
Last Name: <form:errors path="*" cssClass="errors"/>
<br/>
<form:input path="lastName" size="30" maxlength="80" />
</th>
</tr>
<tr>
<td><p class="submit"><input type="submit" value="Find Owners"/></p></td>
</tr>
</table>
</form:form>
<body>
<br/>
<a href='<spring:url value="/owners/new" htmlEscape="true"/>'>Add Owner</a>
<div id="main">
<%@ include file="/WEB-INF/jsp/footer.jsp" %>
<h2>Find Owners:</h2>
<spring:url value="/owners" var="formUrl"/>
<form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get">
<fieldset>
<label class="control-label">Last name:</label>
<div class="controls">
<form:input path="lastName" size="30" maxlength="80"/>
<form:errors path="*" cssClass="errors"/>
</div>
<div>
<button type="submit">Find Owner</button>
</div>
</fieldset>
</form:form>
<br/>
<a href='<spring:url value="/owners/new" htmlEscape="true"/>'>Add Owner</a>
<jsp:include page="../footer.jsp"/>
</div>
</body>
</html>

View file

@ -1,7 +1,16 @@
<%@ include file="/WEB-INF/jsp/includes.jsp" %>
<%@ include file="/WEB-INF/jsp/header.jsp" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<jsp:include page="../header.jsp"/>
<body>
<div id="main">
<h2>Owner Information</h2>
<table>
@ -105,4 +114,9 @@
</table>
</c:forEach>
<%@ include file="/WEB-INF/jsp/footer.jsp" %>
<jsp:include page="../footer.jsp"/>
</div>
</body>
</html>

View file

@ -1,16 +1,29 @@
<%@ include file="/WEB-INF/jsp/includes.jsp" %>
<%@ include file="/WEB-INF/jsp/header.jsp" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<img src="<spring:url value="/static/images/pets.png" htmlEscape="true" />" align="right" style="position:relative;right:30px;">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<jsp:include page="header.jsp"/>
<body>
<div id="main">
<img src="<spring:url value="/resources/images/pets.png" htmlEscape="true" />" align="right" style="position:relative;right:30px;"></img>
<h2><fmt:message key="welcome"/></h2>
<ul>
<li><a href="<spring:url value="/owners/search" htmlEscape="true" />">Find owner</a></li>
<li><a href="<spring:url value="/vets" htmlEscape="true" />">Display all veterinarians</a></li>
<li><a href="<spring:url value="/static/html/tutorial.html" htmlEscape="true" />">Tutorial</a></li>
<li><a href="<spring:url value="/resources/html/tutorial.html" htmlEscape="true" />">Tutorial</a></li>
</ul>
<p>&nbsp;</p>
<p>&nbsp;</p>
<%@ include file="/WEB-INF/jsp/footer.jsp" %>
<jsp:include page="footer.jsp"/>
</div>
</body>
</html>

View file

@ -3,11 +3,12 @@
- DispatcherServlet application context for PetClinic's web tier.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--
- The controllers are autodetected POJOs labeled with the @Controller annotation.
@ -30,7 +31,7 @@
- for request parameter binding. It overrides the default AnnotationMethodHandlerAdapter.
-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<property name="webBindingInitializer">
<bean class="org.springframework.samples.petclinic.web.ClinicBindingInitializer"/>
</property>
</bean>
@ -58,15 +59,21 @@
- BeanNameViewResolver. Note the use of the expression language to refer to the contentType
- property of the vets view bean, setting it to 'application/vnd.springsource.samples.petclinic+xml'.
-->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="xml" value="#{vets.contentType}"/>
<entry key="atom" value="#{visits.contentType}"/>
</map>
</property>
<property name="order" value="0"/>
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="mediaTypes">
<value>
atom=application/atom+xml
xml=#{vets.contentType}
</value>
</property>
</bean>
<!--
- The BeanNameViewResolver is used to pick up the visits view name (below).

View file

@ -20,7 +20,7 @@
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:mappingResources="petclinic.hbm.xml">
<property name="hibernateProperties">
<props>
@ -32,14 +32,14 @@
<property name="eventListeners">
<map>
<entry key="merge">
<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
<bean class="org.springframework.orm.hibernate4.support.IdTransferringMergeEventListener"/>
</entry>
</map>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->

View file

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Before After
Before After

View file

@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
@ -81,18 +82,16 @@ import org.springframework.test.context.junit4.AbstractTransactionalJUnit4Spring
* @author Sam Brannen
*/
@ContextConfiguration
public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests {
public abstract class AbstractClinicTests {
@Autowired
protected Clinic clinic;
@Test
@Test @Transactional
public void getVets() {
Collection<Vet> vets = this.clinic.getVets();
// Use the inherited countRowsInTable() convenience method (from
// AbstractTransactionalJUnit4SpringContextTests) to verify the results.
assertEquals("JDBC query must show the same number of vets", super.countRowsInTable("vets"), vets.size());
Vet v1 = EntityUtils.getById(vets, Vet.class, 2);
assertEquals("Leary", v1.getLastName());
assertEquals(1, v1.getNrOfSpecialties());
@ -107,8 +106,7 @@ public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4Spr
@Test
public void getPetTypes() {
Collection<PetType> petTypes = this.clinic.getPetTypes();
assertEquals("JDBC query must show the same number of pet types", super.countRowsInTable("types"),
petTypes.size());
PetType t1 = EntityUtils.getById(petTypes, PetType.class, 1);
assertEquals("cat", t1.getName());
PetType t4 = EntityUtils.getById(petTypes, PetType.class, 4);

View file

@ -1,8 +1,10 @@
package org.springframework.samples.petclinic.hibernate;
import org.junit.runner.RunWith;
import org.springframework.samples.petclinic.AbstractClinicTests;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
@ -17,6 +19,7 @@ import org.springframework.test.context.ContextConfiguration;
*/
@ContextConfiguration
@DirtiesContext
@RunWith(SpringJUnit4ClassRunner.class)
public class HibernateClinicTests extends AbstractClinicTests {
}

View file

@ -1,12 +1,18 @@
package org.springframework.samples.petclinic.jpa;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import java.util.Collection;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
@ -14,8 +20,6 @@ import org.springframework.samples.petclinic.PetType;
import org.springframework.samples.petclinic.Vet;
import org.springframework.samples.petclinic.Visit;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.test.annotation.ExpectedException;
import org.springframework.test.jpa.AbstractJpaTests;
/**
* <p>
@ -35,13 +39,6 @@ import org.springframework.test.jpa.AbstractJpaTests;
* <li>Executes each test method in its own transaction, which is automatically
* rolled back by default. This means that even if tests insert or otherwise
* change database state, there is no need for a teardown or cleanup script.</li>
* <li>Provides useful inherited protected fields, such as a
* {@link SimpleJdbcTemplate} that can be used to verify database state after
* test operations, or verify the results of queries performed by application
* code. Alternatively, you can use protected convenience methods such as
* {@link #countRowsInTable(String)}, {@link #deleteFromTables(String[])},
* etc. An ApplicationContext is also inherited, and can be used for explicit
* lookup if necessary.</li>
* </ul>
* <p>
* {@link AbstractJpaTests} and related classes are shipped in
@ -52,38 +49,30 @@ import org.springframework.test.jpa.AbstractJpaTests;
* @author Sam Brannen
* @see AbstractJpaTests
*/
public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
public abstract class AbstractJpaClinicTests {
@PersistenceContext
private EntityManager entityManager;
@Autowired
protected Clinic clinic;
/**
* This method is provided to set the Clinic instance being tested by the
* Dependency Injection injection behaviour of the superclass from the
* <code>org.springframework.test</code> package.
*
* @param clinic clinic to test
*/
public void setClinic(Clinic clinic) {
this.clinic = clinic;
}
@ExpectedException(IllegalArgumentException.class)
@Test
public void testBogusJpql() {
this.sharedEntityManager.createQuery("SELECT RUBBISH FROM RUBBISH HEAP").executeUpdate();
try {
this.entityManager.createQuery("SELECT RUBBISH FROM RUBBISH HEAP").executeUpdate();
fail("exception was expected because of incorrect SQL statement");
} catch (Exception e) {
// expected
}
}
public void testApplicationManaged() {
EntityManager appManaged = this.entityManagerFactory.createEntityManager();
appManaged.joinTransaction();
}
@Test
public void testGetVets() {
Collection<Vet> vets = this.clinic.getVets();
// Use the inherited countRowsInTable() convenience method (from
// AbstractTransactionalDataSourceSpringContextTests) to verify the
// results.
assertEquals("JDBC query must show the same number of vets", super.countRowsInTable("vets"), vets.size());
Vet v1 = EntityUtils.getById(vets, Vet.class, 2);
assertEquals("Leary", v1.getLastName());
assertEquals(1, v1.getNrOfSpecialties());
@ -95,16 +84,17 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals("surgery", (v2.getSpecialties().get(1)).getName());
}
@Test
public void testGetPetTypes() {
Collection<PetType> petTypes = this.clinic.getPetTypes();
assertEquals("JDBC query must show the same number of pet types", super.countRowsInTable("types"),
petTypes.size());
PetType t1 = EntityUtils.getById(petTypes, PetType.class, 1);
assertEquals("cat", t1.getName());
PetType t4 = EntityUtils.getById(petTypes, PetType.class, 4);
assertEquals("snake", t4.getName());
}
@Test
public void testFindOwners() {
Collection<Owner> owners = this.clinic.findOwners("Davis");
assertEquals(2, owners.size());
@ -112,21 +102,15 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals(0, owners.size());
}
@Test
public void testLoadOwner() {
Owner o1 = this.clinic.loadOwner(1);
assertTrue(o1.getLastName().startsWith("Franklin"));
Owner o10 = this.clinic.loadOwner(10);
assertEquals("Carlos", o10.getFirstName());
// Check lazy loading, by ending the transaction
endTransaction();
// Now Owners are "disconnected" from the data store.
// We might need to touch this collection if we switched to lazy loading
// in mapping files, but this test would pick this up.
o1.getPets();
}
@Test
public void testInsertOwner() {
Collection<Owner> owners = this.clinic.findOwners("Schultz");
int found = owners.size();
@ -138,6 +122,7 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals(found + 1, owners.size());
}
@Test
public void testUpdateOwner() throws Exception {
Owner o1 = this.clinic.loadOwner(1);
String old = o1.getLastName();
@ -147,6 +132,7 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals(old + "X", o1.getLastName());
}
@Test
public void testLoadPet() {
Collection<PetType> types = this.clinic.getPetTypes();
Pet p7 = this.clinic.loadPet(7);
@ -159,6 +145,7 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals("Peter", p6.getOwner().getFirstName());
}
@Test
public void testInsertPet() {
Owner o6 = this.clinic.loadOwner(6);
int found = o6.getPets().size();
@ -175,6 +162,7 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals(found + 1, o6.getPets().size());
}
@Test
public void testUpdatePet() throws Exception {
Pet p7 = this.clinic.loadPet(7);
String old = p7.getName();
@ -184,6 +172,7 @@ public abstract class AbstractJpaClinicTests extends AbstractJpaTests {
assertEquals(old + "X", p7.getName());
}
@Test
public void testInsertVisit() {
Pet p7 = this.clinic.loadPet(7);
int found = p7.getVisits().size();

View file

@ -2,7 +2,14 @@ package org.springframework.samples.petclinic.jpa;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.aspects.UsageLogAspect;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.assertFalse;
/**
* <p>
@ -17,23 +24,16 @@ import org.springframework.samples.petclinic.aspects.UsageLogAspect;
* @author Rod Johnson
* @author Juergen Hoeller
*/
@ContextConfiguration(locations={"applicationContext-jpaCommon.xml", "applicationContext-hibernateAdapter.xml",
"applicationContext-entityManager.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class EntityManagerClinicTests extends AbstractJpaClinicTests {
@Autowired
private UsageLogAspect usageLogAspect;
public void setUsageLogAspect(UsageLogAspect usageLogAspect) {
this.usageLogAspect = usageLogAspect;
}
@Override
protected String[] getConfigPaths() {
return new String[] {
"applicationContext-jpaCommon.xml",
"applicationContext-toplinkAdapter.xml",
"applicationContext-entityManager.xml"
};
}
@Test
public void testUsageLogAspectIsInvoked() {
String name1 = "Schuurman";
String name2 = "Greenwood";

View file

@ -1,5 +1,9 @@
package org.springframework.samples.petclinic.jpa;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Tests for the DAO variant based on the shared EntityManager approach, using
@ -12,15 +16,9 @@ package org.springframework.samples.petclinic.jpa;
*
* @author Juergen Hoeller
*/
@ContextConfiguration(locations={"applicationContext-jpaCommon.xml", "applicationContext-hibernateAdapter.xml",
"applicationContext-entityManager.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class HibernateEntityManagerClinicTests extends EntityManagerClinicTests {
@Override
protected String[] getConfigPaths() {
return new String[] {
"applicationContext-jpaCommon.xml",
"applicationContext-hibernateAdapter.xml",
"applicationContext-entityManager.xml"
};
}
}

View file

@ -1,27 +0,0 @@
package org.springframework.samples.petclinic.jpa;
/**
* <p>
* Tests for the DAO variant based on the shared EntityManager approach, using
* Apache OpenJPA for testing instead of the reference implementation.
* </p>
* <p>
* Specifically tests usage of an <code>orm.xml</code> file, loaded by the
* persistence provider through the Spring-provided persistence unit root URL.
* </p>
*
* @author Juergen Hoeller
*/
public class OpenJpaEntityManagerClinicTests extends EntityManagerClinicTests {
@Override
protected String[] getConfigPaths() {
return new String[] {
"applicationContext-jpaCommon.xml",
"applicationContext-openJpaAdapter.xml",
"applicationContext-entityManager.xml"
};
}
}

View file

@ -1,13 +1,13 @@
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.samples.petclinic.hibernate.HibernateClinic">
<constructor-arg ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:mappingResources="petclinic.hbm.xml">
<property name="hibernateProperties">
<props>
@ -15,16 +15,9 @@
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="eventListeners">
<map>
<entry key="merge">
<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
</entry>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

View file

@ -1,9 +0,0 @@
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" p:database="${jpa.database}"
p:showSql="${jpa.showSql}" />
</beans>

View file

@ -1,9 +0,0 @@
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter"
p:databasePlatform="${jpa.databasePlatform}" p:showSql="${jpa.showSql}" />
</beans>