Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • s51119/broken-petclinic
  • s72462/broken-petclinic
  • s61200/broken-petclinic
  • s76620/broken-petclinic
  • s76545/broken-petclinic
  • s76915/broken-petclinic
  • s70130/broken-petclinic
  • s72523/broken-petclinic
  • s77047/broken-petclinic
  • s70178/broken-petclinic
  • s76522/broken-petclinic
  • s76426/broken-petclinic
  • s76863/broken-petclinic
  • s76856/broken-petclinic
  • s76728/broken-petclinic
  • williamreetz/broken-petclinic
  • s77034/broken-petclinic
  • s76400/broken-petclinic
  • s72288/broken-petclinic
  • s76608/broken-petclinic
20 results
Show changes
Showing
with 425 additions and 1389 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>petclinic-classic</artifactId>
<name>petclinic-classic</name>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<properties>
<spring.version>3.0.0.RC2</spring.version>
<slf4j.version>1.5.6</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>com.oracle.toplink.essentials</groupId>
<artifactId>com.springsource.oracle.toplink.essentials</artifactId>
<version>2.0.0.b41-beta2</version>
</dependency>
<dependency>
<groupId>com.sun.syndication</groupId>
<artifactId>com.springsource.com.sun.syndication</artifactId>
<version>1.0.0</version>
</dependency>
<!--
<dependency>
<groupId>javax.el</groupId>
<artifactId>com.springsource.javax.el</artifactId>
<version>1.0.0</version>
<scope>provided</scope>
</dependency>
-->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>com.springsource.javax.persistence</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>com.springsource.javax.servlet</artifactId>
<version>2.5.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>com.springsource.javax.servlet.jsp</artifactId>
<version>2.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>com.springsource.javax.servlet.jsp.jstl</artifactId>
<version>1.2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>com.springsource.javax.xml.bind</artifactId>
<version>2.1.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.dbcp</artifactId>
<version>1.2.2.osgi</version>
</dependency>
<dependency>
<groupId>org.apache.log4j</groupId>
<artifactId>com.springsource.org.apache.log4j</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>com.springsource.org.apache.openjpa</artifactId>
<version>1.1.0</version>
</dependency>
<!--
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>com.springsource.org.apache.taglibs.standard</artifactId>
<version>1.1.2</version>
<scope>provided</scope>
</dependency>
-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>com.springsource.org.hibernate</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>com.springsource.org.hibernate.ejb</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>com.springsource.org.hsqldb</artifactId>
<version>1.8.0.9</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>com.springsource.org.jdom</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.asm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.web.servlet</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.junit</groupId>
<artifactId>com.springsource.org.junit</artifactId>
<version>4.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>com.springsource.javax.transaction</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>com.springsource.org.hibernate.annotations</artifactId>
<version>3.4.0.GA</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>com.springsource.slf4j.org.apache.commons.logging</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>com.springsource.slf4j.api</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>com.springsource.slf4j.log4j</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.log4j</groupId>
<artifactId>com.springsource.org.apache.log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<repositories>
<repository>
<id>com.springsource.repository.bundles.release</id>
<name>SpringSource Enterprise Bundle Repository - SpringSource Releases</name>
<url>http://repository.springsource.com/maven/bundles/release</url>
</repository>
<repository>
<id>com.springsource.repository.bundles.milestone</id>
<name>SpringSource Enterprise Bundle Repository - SpringSource Milestones</name>
<url>http://repository.springsource.com/maven/bundles/milestone</url>
</repository>
<repository>
<id>com.springsource.repository.bundles.external</id>
<name>SpringSource Enterprise Bundle Repository - External Releases</name>
<url>http://repository.springsource.com/maven/bundles/external</url>
</repository>
<repository>
<id>com.springsource.repository.bundles.snapshot</id>
<name>SpringSource Enterprise Bundle Repository - Snapshot Releases</name>
<url>http://repository.springsource.com/maven/bundles/snapshot</url>
</repository>
<repository>
<id>spring-release</id>
<name>Spring Portfolio Release Repository</name>
<url>http://maven.springframework.org/release</url>
</repository>
<repository>
<id>spring-external</id>
<name>Spring Portfolio External Repository</name>
<url>http://maven.springframework.org/external</url>
</repository>
<repository>
<id>spring-milestone</id>
<name>Spring Portfolio Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-petclinic</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<name>petclinic</name>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web dependencies -->
<webjars-bootstrap.version>3.3.6</webjars-bootstrap.version>
<webjars-jquery-ui.version>1.11.4</webjars-jquery-ui.version>
<webjars-jquery.version>2.2.4</webjars-jquery.version>
<wro4j.version>1.8.0</wro4j.version>
<jacoco.version>0.8.2</jacoco.version>
</properties>
<dependencies>
<!-- Spring and Spring Boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Databases - Uses HSQL by default -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- caching -->
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<!-- webjars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>${webjars-jquery.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery-ui</artifactId>
<version>${webjars-jquery-ui.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${webjars-bootstrap.version}</version>
</dependency>
<!-- end of webjars -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<!-- Spring Boot Actuator displays build-related information
if a META-INF/build-info.properties file is present -->
<goals>
<goal>build-info</goal>
</goals>
<configuration>
<additionalProperties>
<encoding.source>${project.build.sourceEncoding}</encoding.source>
<encoding.reporting>${project.reporting.outputEncoding}</encoding.reporting>
<java.source>${maven.compiler.source}</java.source>
<java.target>${maven.compiler.target}</java.target>
</additionalProperties>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Spring Boot Actuator displays build-related information if a git.properties
file is present at the classpath -->
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration>
<verbose>true</verbose>
<dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat>
<generateGitPropertiesFile>true</generateGitPropertiesFile>
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties
</generateGitPropertiesFilename>
<failOnNoGitDirectory>false</failOnNoGitDirectory>
</configuration>
</plugin>
<plugin>
<groupId>ro.isdc.wro4j</groupId>
<artifactId>wro4j-maven-plugin</artifactId>
<version>${wro4j.version}</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
<configuration>
<wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
<cssDestinationFolder>${project.build.directory}/classes/static/resources/css</cssDestinationFolder>
<wroFile>${basedir}/src/main/wro/wro.xml</wroFile>
<extraConfigFile>${basedir}/src/main/wro/wro.properties</extraConfigFile>
<contextFolder>${basedir}/src/main/less</contextFolder>
</configuration>
<dependencies>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${webjars-bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<!-- Apache 2 license -->
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0</url>
</license>
</licenses>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
# Spring PetClinic Sample Application [![Build Status](https://travis-ci.org/spring-projects/spring-petclinic.png?branch=master)](https://travis-ci.org/spring-projects/spring-petclinic/)
## Understanding the Spring Petclinic application with a few diagrams
<a href="https://speakerdeck.com/michaelisvy/spring-petclinic-sample-application">See the presentation here</a>
## Running petclinic locally
Petclinic is a [Spring Boot](https://spring.io/guides/gs/spring-boot) application built using [Maven](https://spring.io/guides/gs/maven/). You can build a jar file and run it from the command line:
```
git clone https://github.com/spring-projects/spring-petclinic.git
cd spring-petclinic
./mvnw package
java -jar target/*.jar
```
You can then access petclinic here: http://localhost:8080/
<img width="1042" alt="petclinic-screenshot" src="https://cloud.githubusercontent.com/assets/838318/19727082/2aee6d6c-9b8e-11e6-81fe-e889a5ddfded.png">
Or you can run it from Maven directly using the Spring Boot Maven plugin. If you do this it will pick up changes that you make in the project immediately (changes to Java source files require a compile as well - most people use an IDE for this):
```
./mvnw spring-boot:run
```
## In case you find a bug/suggested improvement for Spring Petclinic
Our issue tracker is available here: https://github.com/spring-projects/spring-petclinic/issues
## Database configuration
In its default configuration, Petclinic uses an in-memory database (HSQLDB) which
gets populated at startup with data. A similar setup is provided for MySql in case a persistent database configuration is needed.
Note that whenever the database type is changed, the app needs to be run with a different profile: `spring.profiles.active=mysql` for MySql.
You could start MySql locally with whatever installer works for your OS, or with docker:
```
docker run -e MYSQL_ROOT_PASSWORD=petclinic -e MYSQL_DATABASE=petclinic -p 3306:3306 mysql:5.7.8
```
## Working with Petclinic in your IDE
### Prerequisites
The following items should be installed in your system:
* Java 8 or newer.
* git command line tool (https://help.github.com/articles/set-up-git)
* Your prefered IDE
* Eclipse with the m2e plugin. Note: when m2e is available, there is an m2 icon in `Help -> About` dialog. If m2e is
not there, just follow the install process here: https://www.eclipse.org/m2e/
* [Spring Tools Suite](https://spring.io/tools) (STS)
* IntelliJ IDEA
### Steps:
1) On the command line
```
git clone https://github.com/spring-projects/spring-petclinic.git
```
2) Inside Eclipse or STS
```
File -> Import -> Maven -> Existing Maven project
```
Then either build on the command line `./mvnw generate-resources` or using the Eclipse launcher (right click on project and `Run As -> Maven install`) to generate the css. Run the application main method by right clicking on it and choosing `Run As -> Java Application`.
3) Inside IntelliJ IDEA
In the main menu, choose `File -> Open` and select the Petclinic [pom.xml](pom.xml). Click on the `Open` button.
CSS files are generated from the Maven build. You can either build them on the command line `./mvnw generate-resources`
or right click on the `spring-petclinic` project then `Maven -> Generates sources and Update Folders`.
A run configuration named `PetClinicApplication` should have been created for you if you're using a recent Ultimate
version. Otherwise, run the application by right clicking on the `PetClinicApplication` main class and choosing
`Run 'PetClinicApplication'`.
4) Navigate to Petclinic
Visit [http://localhost:8080](http://localhost:8080) in your browser.
## Looking for something in particular?
|Spring Boot Configuration | Class or Java property files |
|--------------------------|---|
|The Main Class | [PetClinicApplication](https://github.com/spring-projects/spring-petclinic/blob/master/src/main/java/org/springframework/samples/petclinic/PetClinicApplication.java) |
|Properties Files | [application.properties](https://github.com/spring-projects/spring-petclinic/blob/master/src/main/resources) |
|Caching | [CacheConfiguration](https://github.com/spring-projects/spring-petclinic/blob/master/src/main/java/org/springframework/samples/petclinic/system/CacheConfiguration.java) |
## Interesting Spring Petclinic branches and forks
The Spring Petclinic master branch in the main [spring-projects](https://github.com/spring-projects/spring-petclinic)
GitHub org is the "canonical" implementation, currently based on Spring Boot and Thymeleaf. There are
[quite a few forks](https://spring-petclinic.github.io/docs/forks.html) in a special GitHub org
[spring-petclinic](https://github.com/spring-petclinic). If you have a special interest in a different technology stack
that could be used to implement the Pet Clinic then please join the community there.
## Interaction with other open source projects
One of the best parts about working on the Spring Petclinic application is that we have the opportunity to work in direct contact with many Open Source projects. We found some bugs/suggested improvements on various topics such as Spring, Spring Data, Bean Validation and even Eclipse! In many cases, they've been fixed/implemented in just a few days.
Here is a list of them:
| Name | Issue |
|------|-------|
| Spring JDBC: simplify usage of NamedParameterJdbcTemplate | [SPR-10256](https://jira.springsource.org/browse/SPR-10256) and [SPR-10257](https://jira.springsource.org/browse/SPR-10257) |
| Bean Validation / Hibernate Validator: simplify Maven dependencies and backward compatibility |[HV-790](https://hibernate.atlassian.net/browse/HV-790) and [HV-792](https://hibernate.atlassian.net/browse/HV-792) |
| Spring Data: provide more flexibility when working with JPQL queries | [DATAJPA-292](https://jira.springsource.org/browse/DATAJPA-292) |
# Contributing
The [issue tracker](https://github.com/spring-projects/spring-petclinic/issues) is the preferred channel for bug reports, features requests and submitting pull requests.
For pull requests, editor preferences are available in the [editor config](.editorconfig) for easy use in common text editors. Read more and download plugins at <https://editorconfig.org>. If you have not previously done so, please fill out and submit the [Contributor License Agreement](https://cla.pivotal.io/sign/spring).
# License
The Spring PetClinic sample application is released under version 2.0 of the [Apache License](https://www.apache.org/licenses/LICENSE-2.0).
[spring-petclinic]: https://github.com/spring-projects/spring-petclinic
[spring-framework-petclinic]: https://github.com/spring-petclinic/spring-framework-petclinic
[spring-petclinic-angularjs]: https://github.com/spring-petclinic/spring-petclinic-angularjs
[javaconfig branch]: https://github.com/spring-petclinic/spring-framework-petclinic/tree/javaconfig
[spring-petclinic-angular]: https://github.com/spring-petclinic/spring-petclinic-angular
[spring-petclinic-microservices]: https://github.com/spring-petclinic/spring-petclinic-microservices
[spring-petclinic-reactjs]: https://github.com/spring-petclinic/spring-petclinic-reactjs
[spring-petclinic-graphql]: https://github.com/spring-petclinic/spring-petclinic-graphql
[spring-petclinic-kotlin]: https://github.com/spring-petclinic/spring-petclinic-kotlin
[spring-petclinic-rest]: https://github.com/spring-petclinic/spring-petclinic-rest
==========================================================================
=== Spring PetClinic Sample Application
==========================================================================
@author Ken Krebs
@author Juergen Hoeller
@author Rob Harrop
@author Costin Leau
@author Sam Brannen
@author Scott Andrews
==========================================================================
=== Data Access Strategies
==========================================================================
PetClinic features alternative DAO implementations and application
configurations for JDBC, Hibernate, and JPA, with HSQLDB and MySQL as
target databases. The default PetClinic configuration is JDBC on HSQLDB.
See "src/main/resources/jdbc.properties" as well as web.xml and
applicationContext-*.xml in the "src/main/webapp/WEB-INF" folder for
details. A simple comment change in web.xml switches between the data
access strategies.
The JDBC and Hibernate versions of PetClinic also demonstrate JMX support
via the use of <context:mbean-export/> for exporting MBeans.
SimpleJdbcClinic exposes the SimpleJdbcClinicMBean management interface
via JMX through the use of the @ManagedResource and @ManagedOperation
annotations; whereas, the HibernateStatistics service is exposed via JMX
through auto-detection of the service MBean. You can start up the JDK's
JConsole to manage the exported bean.
All data access strategies can work with JTA for transaction management by
activating the JtaTransactionManager and a JndiObjectFactoryBean that
refers to a transactional container DataSource. The default for JDBC is
DataSourceTransactionManager; for Hibernate, HibernateTransactionManager;
for JPA, JpaTransactionManager. Those local strategies allow for working
with any locally defined DataSource.
Note that the sample configurations for JDBC, Hibernate, and JPA configure
a BasicDataSource from the Apache Commons DBCP project for connection
pooling.
==========================================================================
=== Build and Deployment
==========================================================================
The Spring PetClinic sample application is built using Maven.
When the project is first built, Maven will automatically download all required
dependencies (if these haven't been downloaded before). Thus the initial build
may take a few minutes depending on the speed of your Internet connection,
but subsequent builds will be much faster.
Available build commands:
- mvn clean --> cleans the project
- mvn clean test --> cleans the project and runs all tests
- mvn clean package --> cleans the project and builds the WAR
After building the project with "mvn clean package", you will find the
resulting WAR file in the "target/" directory. By default, an
embedded HSQLDB instance in configured. No other steps are necessary to
get the data source up and running: you can simply deploy the built WAR
file directly to your Servlet container.
For MySQL, you'll need to use the corresponding schema and SQL scripts in
the "db/mysql" subdirectory. Follow the steps outlined in
"db/mysql/petclinic_db_setup_mysql.txt" for explicit details.
In you intend to use a local DataSource, the JDBC settings can be adapted
in "src/main/resources/jdbc.properties". To use a JTA DataSource, you need
to set up corresponding DataSources in your Java EE container.
Notes on enabling Log4J:
- Log4J is disabled by default due to issues with JBoss.
- Uncomment the Log4J listener in "WEB-INF/web.xml" to enable logging.
==========================================================================
=== JPA on Tomcat
==========================================================================
This section provides tips on using the Java Persistence API (JPA) on
Apache Tomcat 4.x or higher with a persistence provider that requires
class instrumentation (such as TopLink Essentials).
To use JPA class instrumentation, Tomcat has to be instructed to use a
custom class loader which supports instrumentation. See the JPA section of
the Spring reference manual for complete details.
The basic steps are:
- Copy "org.springframework.instrument.tomcat-3.0.0.RELEASE.jar" from the
Spring distribution to "TOMCAT_HOME/server/lib".
- If you're running on Tomcat 5.x, modify "TOMCAT_HOME/conf/server.xml"
and add a new "<Context>" element for 'petclinic' (see below). You can
alternatively deploy the WAR including "META-INF/context.xml" from this
sample application's "src/main/webapp" directory, in which case you
will need to uncomment the Loader element in that file to enable the
use of the TomcatInstrumentableClassLoader.
<Context path="/petclinic" docBase="/petclinic/location" ...>
<!-- please note that useSystemClassLoaderAsParent is available since Tomcat 5.5.20; remove it if previous versions are being used -->
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader" useSystemClassLoaderAsParent="false"/>
...
</Context>
package org.springframework.samples.petclinic;
/**
* Simple JavaBean domain object with an id property.
* Used as a base class for objects needing this property.
*
* @author Ken Krebs
* @author Juergen Hoeller
*/
public class BaseEntity {
private Integer id;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public boolean isNew() {
return (this.id == null);
}
}
package org.springframework.samples.petclinic;
import java.util.Collection;
import org.springframework.dao.DataAccessException;
/**
* The high-level PetClinic business interface.
*
* <p>This is basically a data access object.
* PetClinic doesn't have a dedicated business facade.
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Sam Brannen
*/
public interface Clinic {
/**
* Retrieve all <code>Vet</code>s from the data store.
* @return a <code>Collection</code> of <code>Vet</code>s
*/
Collection<Vet> getVets() throws DataAccessException;
/**
* Retrieve all <code>PetType</code>s from the data store.
* @return a <code>Collection</code> of <code>PetType</code>s
*/
Collection<PetType> getPetTypes() throws DataAccessException;
/**
* Retrieve <code>Owner</code>s from the data store by last name,
* returning all owners whose last name <i>starts</i> with the given name.
* @param lastName Value to search for
* @return a <code>Collection</code> of matching <code>Owner</code>s
* (or an empty <code>Collection</code> if none found)
*/
Collection<Owner> findOwners(String lastName) throws DataAccessException;
/**
* Retrieve an <code>Owner</code> from the data store by id.
* @param id the id to search for
* @return the <code>Owner</code> if found
* @throws org.springframework.dao.DataRetrievalFailureException if not found
*/
Owner loadOwner(int id) throws DataAccessException;
/**
* Retrieve a <code>Pet</code> from the data store by id.
* @param id the id to search for
* @return the <code>Pet</code> if found
* @throws org.springframework.dao.DataRetrievalFailureException if not found
*/
Pet loadPet(int id) throws DataAccessException;
/**
* Save an <code>Owner</code> to the data store, either inserting or updating it.
* @param owner the <code>Owner</code> to save
* @see BaseEntity#isNew
*/
void storeOwner(Owner owner) throws DataAccessException;
/**
* Save a <code>Pet</code> to the data store, either inserting or updating it.
* @param pet the <code>Pet</code> to save
* @see BaseEntity#isNew
*/
void storePet(Pet pet) throws DataAccessException;
/**
* Save a <code>Visit</code> to the data store, either inserting or updating it.
* @param visit the <code>Visit</code> to save
* @see BaseEntity#isNew
*/
void storeVisit(Visit visit) throws DataAccessException;
/**
* Deletes a <code>Pet</code> from the data store.
*/
void deletePet(int id) throws DataAccessException;
}
package org.springframework.samples.petclinic;
/**
* Simple JavaBean domain object adds a name property to <code>BaseEntity</code>.
* Used as a base class for objects needing these properties.
*
* @author Ken Krebs
* @author Juergen Hoeller
*/
public class NamedEntity extends BaseEntity {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.getName();
}
}
package org.springframework.samples.petclinic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.support.MutableSortDefinition;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.core.style.ToStringCreator;
/**
* Simple JavaBean domain object representing an owner.
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Sam Brannen
*/
public class Owner extends Person {
private String address;
private String city;
private String telephone;
private Set<Pet> pets;
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
protected void setPetsInternal(Set<Pet> pets) {
this.pets = pets;
}
protected Set<Pet> getPetsInternal() {
if (this.pets == null) {
this.pets = new HashSet<Pet>();
}
return this.pets;
}
public List<Pet> getPets() {
List<Pet> sortedPets = new ArrayList<Pet>(getPetsInternal());
PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", true, true));
return Collections.unmodifiableList(sortedPets);
}
public void addPet(Pet pet) {
getPetsInternal().add(pet);
pet.setOwner(this);
}
/**
* Return the Pet with the given name, or null if none found for this Owner.
*
* @param name to test
* @return true if pet name is already in use
*/
public Pet getPet(String name) {
return getPet(name, false);
}
/**
* Return the Pet with the given name, or null if none found for this Owner.
*
* @param name to test
* @return true if pet name is already in use
*/
public Pet getPet(String name, boolean ignoreNew) {
name = name.toLowerCase();
for (Pet pet : getPetsInternal()) {
if (!ignoreNew || !pet.isNew()) {
String compName = pet.getName();
compName = compName.toLowerCase();
if (compName.equals(name)) {
return pet;
}
}
}
return null;
}
@Override
public String toString() {
return new ToStringCreator(this)
.append("id", this.getId())
.append("new", this.isNew())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
}
}
package org.springframework.samples.petclinic;
/**
* Simple JavaBean domain object representing an person.
*
* @author Ken Krebs
*/
public class Person extends BaseEntity {
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
package org.springframework.samples.petclinic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.support.MutableSortDefinition;
import org.springframework.beans.support.PropertyComparator;
/**
* Simple JavaBean business object representing a pet.
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Sam Brannen
*/
public class Pet extends NamedEntity {
private Date birthDate;
private PetType type;
private Owner owner;
private Set<Visit> visits;
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Date getBirthDate() {
return this.birthDate;
}
public void setType(PetType type) {
this.type = type;
}
public PetType getType() {
return this.type;
}
protected void setOwner(Owner owner) {
this.owner = owner;
}
public Owner getOwner() {
return this.owner;
}
protected void setVisitsInternal(Set<Visit> visits) {
this.visits = visits;
}
protected Set<Visit> getVisitsInternal() {
if (this.visits == null) {
this.visits = new HashSet<Visit>();
}
return this.visits;
}
public List<Visit> getVisits() {
List<Visit> sortedVisits = new ArrayList<Visit>(getVisitsInternal());
PropertyComparator.sort(sortedVisits, new MutableSortDefinition("date", false, false));
return Collections.unmodifiableList(sortedVisits);
}
public void addVisit(Visit visit) {
getVisitsInternal().add(visit);
visit.setPet(this);
}
}
/*
* Copyright 2012-2019 the original author or authors.
*
* 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
*
* https://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.
*/
package org.springframework.samples.petclinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* PetClinic Spring Boot Application.
*
* @author Dave Syer
*
*/
@SpringBootApplication
public class PetClinicApplication {
public static void main(String[] args) {
SpringApplication.run(PetClinicApplication.class, args)
}
}
package org.springframework.samples.petclinic;
/**
* @author Juergen Hoeller
*/
public class PetType extends NamedEntity {
}
package org.springframework.samples.petclinic;
/**
* Models a {@link Vet Vet's} specialty (for example, dentistry).
*
* @author Juergen Hoeller
*/
public class Specialty extends NamedEntity {
}
package org.springframework.samples.petclinic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlElement;
import org.springframework.beans.support.MutableSortDefinition;
import org.springframework.beans.support.PropertyComparator;
/**
* Simple JavaBean domain object representing a veterinarian.
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Sam Brannen
* @author Arjen Poutsma
*/
public class Vet extends Person {
private Set<Specialty> specialties;
protected void setSpecialtiesInternal(Set<Specialty> specialties) {
this.specialties = specialties;
}
protected Set<Specialty> getSpecialtiesInternal() {
if (this.specialties == null) {
this.specialties = new HashSet<Specialty>();
}
return this.specialties;
}
@XmlElement
public List<Specialty> getSpecialties() {
List<Specialty> sortedSpecs = new ArrayList<Specialty>(getSpecialtiesInternal());
PropertyComparator.sort(sortedSpecs, new MutableSortDefinition("name", true, true));
return Collections.unmodifiableList(sortedSpecs);
}
public int getNrOfSpecialties() {
return getSpecialtiesInternal().size();
}
public void addSpecialty(Specialty specialty) {
getSpecialtiesInternal().add(specialty);
}
}
package org.springframework.samples.petclinic;
import java.util.Date;
/**
* Simple JavaBean domain object representing a visit.
*
* @author Ken Krebs
*/
public class Visit extends BaseEntity {
/** Holds value of property date. */
private Date date;
/** Holds value of property description. */
private String description;
/** Holds value of property pet. */
private Pet pet;
/** Creates a new instance of Visit for the current date */
public Visit() {
this.date = new Date();
}
/** Getter for property date.
* @return Value of property date.
*/
public Date getDate() {
return this.date;
}
/** Setter for property date.
* @param date New value of property date.
*/
public void setDate(Date date) {
this.date = date;
}
/** Getter for property description.
* @return Value of property description.
*/
public String getDescription() {
return this.description;
}
/** Setter for property description.
* @param description New value of property description.
*/
public void setDescription(String description) {
this.description = description;
}
/** Getter for property pet.
* @return Value of property pet.
*/
public Pet getPet() {
return this.pet;
}
/** Setter for property pet.
* @param pet New value of property pet.
*/
public void setPet(Pet pet) {
this.pet = pet;
}
}
package org.springframework.samples.petclinic.aspects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
* Aspect to illustrate Spring-driven load-time weaving.
*
* @author Ramnivas Laddad
* @since 2.5
*/
@Aspect
public abstract class AbstractTraceAspect {
private static final Log logger = LogFactory.getLog(AbstractTraceAspect.class);
@Pointcut
public abstract void traced();
@Before("traced()")
public void trace(JoinPoint.StaticPart jpsp) {
if (logger.isTraceEnabled()) {
logger.trace("Entering " + jpsp.getSignature().toLongString());
}
}
}
package org.springframework.samples.petclinic.aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.StopWatch;
/**
* Simple AspectJ aspect that monitors call count and call invocation time.
* Implements the CallMonitor management interface.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.5
*/
@ManagedResource("petclinic:type=CallMonitor")
@Aspect
public class CallMonitoringAspect {
private boolean isEnabled = true;
private int callCount = 0;
private long accumulatedCallTime = 0;
@ManagedAttribute
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
@ManagedAttribute
public boolean isEnabled() {
return isEnabled;
}
@ManagedOperation
public void reset() {
this.callCount = 0;
this.accumulatedCallTime = 0;
}
@ManagedAttribute
public int getCallCount() {
return callCount;
}
@ManagedAttribute
public long getCallTime() {
return (this.callCount > 0 ? this.accumulatedCallTime / this.callCount : 0);
}
@Around("within(@org.springframework.stereotype.Service *)")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
if (this.isEnabled) {
StopWatch sw = new StopWatch(joinPoint.toShortString());
sw.start("invoke");
try {
return joinPoint.proceed();
}
finally {
sw.stop();
synchronized (this) {
this.callCount++;
this.accumulatedCallTime += sw.getTotalTimeMillis();
}
}
}
else {
return joinPoint.proceed();
}
}
}
package org.springframework.samples.petclinic.aspects;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* Sample AspectJ annotation-style aspect that saves
* every owner name requested to the clinic.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 2.0
*/
@Aspect
public class UsageLogAspect {
private int historySize = 100;
// Of course saving all names is not suitable for
// production use, but this is a simple example.
private List<String> namesRequested = new ArrayList<String>(this.historySize);
public synchronized void setHistorySize(int historySize) {
this.historySize = historySize;
this.namesRequested = new ArrayList<String>(historySize);
}
@Before("execution(* *.findOwners(String)) && args(name)")
public synchronized void logNameRequest(String name) {
// Not the most efficient implementation,
// but we're aiming to illustrate the power of
// @AspectJ AOP, not write perfect code here :-)
if (this.namesRequested.size() > this.historySize) {
this.namesRequested.remove(0);
}
this.namesRequested.add(name);
}
public synchronized List<String> getNamesRequested() {
return Collections.unmodifiableList(this.namesRequested);
}
}
/*
* Copyright 2002-2008 the original author or authors.
*
* 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.
*/
package org.springframework.samples.petclinic.config;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource;
/**
* A factory that creates a data source fit for use in a system environment. Creates a DBCP simple data source
* from the provided connection properties.
*
* This factory returns a fully-initialized DataSource implementation. When the DataSource is returned, callers are
* guaranteed that the database schema and data will have been loaded by that time.
*
* Is a FactoryBean, for exposing the fully-initialized DataSource as a Spring bean. See {@link #getObject()}.
*
* @author Chris Beams
* @author Scott Andrews
*/
public class DbcpDataSourceFactory implements FactoryBean<DataSource>, DisposableBean {
// configurable properties
private String driverClassName;
private String url;
private String username;
private String password;
private boolean populate;
private Resource schemaLocation;
private Resource dataLocation;
private Resource dropLocation;
/**
* The object created by this factory.
*/
private BasicDataSource dataSource;
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
/**
* The data source connection URL
*/
public void setUrl(String url) {
this.url = url;
}
/**
* The data source username
*/
public void setUsername(String username) {
this.username = username;
}
/**
*The data source password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Indicates that the data base should be populated from the schema and data locations
*/
public void setPopulate(boolean populate) {
this.populate = populate;
}
/**
* Sets the location of the file containing the schema DDL to export to the database.
* @param schemaLocation the location of the database schema DDL
*/
public void setSchemaLocation(Resource schemaLocation) {
this.schemaLocation = schemaLocation;
}
/**
* Sets the location of the file containing the data to load into the database.
* @param testDataLocation the location of the data file
*/
public void setDataLocation(Resource testDataLocation) {
this.dataLocation = testDataLocation;
}
/**
* Sets the location of the file containing the drop scripts for the database.
* @param testDataLocation the location of the data file
*/
public void setDropLocation(Resource testDropLocation) {
this.dropLocation = testDropLocation;
}
// implementing FactoryBean
// this method is called by Spring to expose the DataSource as a bean
public DataSource getObject() throws Exception {
if (dataSource == null) {
initDataSource();
}
return dataSource;
}
public Class<DataSource> getObjectType() {
return DataSource.class;
}
public boolean isSingleton() {
return true;
}
// implementing DisposableBean
public void destroy() throws Exception {
dataSource.close();
}
// internal helper methods
// encapsulates the steps involved in initializing the data source: creating it, and populating it
private void initDataSource() {
// create the database source first
this.dataSource = createDataSource();
if (this.populate) {
// now populate the database by loading the schema and data
populateDataSource();
}
}
private BasicDataSource createDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
return dataSource;
}
private void populateDataSource() {
DatabasePopulator populator = new DatabasePopulator(dataSource);
if (dropLocation != null) {
try {
populator.populate(this.dropLocation);
}
catch (Exception e) {
// ignore
}
}
populator.populate(this.schemaLocation);
populator.populate(this.dataLocation);
}
/**
* Populates a in memory data source with data.
*/
private class DatabasePopulator {
private DataSource dataSource;
/**
* Creates a new database populator.
* @param dataSource the data source that will be populated.
*/
public DatabasePopulator(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Populate the database executing the statements in the provided resource against the database
* @param sqlFile spring resource containing SQL to run against the db
*/
public void populate(Resource sqlFile) {
Connection connection = null;
try {
connection = dataSource.getConnection();
try {
String sql = parseSqlIn(sqlFile);
executeSql(sql, connection);
} catch (IOException e) {
throw new RuntimeException("I/O exception occurred accessing the database schema file", e);
} catch (SQLException e) {
throw new RuntimeException("SQL exception occurred exporting database schema", e);
}
} catch (SQLException e) {
throw new RuntimeException("SQL exception occurred acquiring connection", e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
}
}
}
// utility method to read a .sql txt input stream
private String parseSqlIn(Resource resource) throws IOException {
InputStream is = null;
try {
is = resource.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringWriter sw = new StringWriter();
BufferedWriter writer = new BufferedWriter(sw);
for (int c=reader.read(); c != -1; c=reader.read()) {
writer.write(c);
}
writer.flush();
return sw.toString();
} finally {
if (is != null) {
is.close();
}
}
}
// utility method to run the parsed sql
private void executeSql(String sql, Connection connection) throws SQLException {
Statement statement = connection.createStatement();
statement.execute(sql);
}
}
}
package org.springframework.samples.petclinic.hibernate;
import java.util.Collection;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
import org.springframework.samples.petclinic.PetType;
import org.springframework.samples.petclinic.Vet;
import org.springframework.samples.petclinic.Visit;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Hibernate implementation of the Clinic interface.
*
* <p>The mappings are defined in "petclinic.hbm.xml", located in the root of the
* class path.
*
* <p>Note that transactions are declared with annotations and that some methods
* contain "readOnly = true" which is an optimization that is particularly
* valuable when using Hibernate (to suppress unnecessary flush attempts for
* read-only operations).
*
* @author Juergen Hoeller
* @author Sam Brannen
* @author Mark Fisher
* @since 19.10.2003
*/
@Repository
@Transactional
public class HibernateClinic implements Clinic {
private SessionFactory sessionFactory;
@Autowired
public HibernateClinic(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public Collection<Vet> getVets() {
return sessionFactory.getCurrentSession().createQuery("from Vet vet order by vet.lastName, vet.firstName").list();
}
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public Collection<PetType> getPetTypes() {
return sessionFactory.getCurrentSession().createQuery("from PetType type order by type.name").list();
}
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public Collection<Owner> findOwners(String lastName) {
return sessionFactory.getCurrentSession().createQuery("from Owner owner where owner.lastName like :lastName")
.setString("lastName", lastName + "%").list();
}
@Transactional(readOnly = true)
public Owner loadOwner(int id) {
return (Owner) sessionFactory.getCurrentSession().load(Owner.class, id);
}
@Transactional(readOnly = true)
public Pet loadPet(int id) {
return (Pet) sessionFactory.getCurrentSession().load(Pet.class, id);
}
public void storeOwner(Owner owner) {
// Note: Hibernate3's merge operation does not reassociate the object
// with the current Hibernate Session. Instead, it will always copy the
// state over to a registered representation of the entity. In case of a
// new entity, it will register a copy as well, but will not update the
// id of the passed-in object. To still update the ids of the original
// objects too, we need to register Spring's
// IdTransferringMergeEventListener on our SessionFactory.
sessionFactory.getCurrentSession().merge(owner);
}
public void storePet(Pet pet) {
sessionFactory.getCurrentSession().merge(pet);
}
public void storeVisit(Visit visit) {
sessionFactory.getCurrentSession().merge(visit);
}
public void deletePet(int id) throws DataAccessException {
Pet pet = loadPet(id);
sessionFactory.getCurrentSession().delete(pet);
}
}
/**
*
* The classes in this package represent the Hibernate implementation
* of PetClinic's persistence layer.
*
*/
package org.springframework.samples.petclinic.hibernate;