A sample Spring-based application

Overview

Spring PetClinic Sample Application Build Status

Understanding the Spring Petclinic application with a few diagrams

See the presentation here

Running petclinic locally

Petclinic is a Spring Boot application built using 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/

petclinic-screenshot

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 (H2) which gets populated at startup with data. The h2 console is automatically exposed at http://localhost:8080/h2-console and it is possible to inspect the content of the database using the jdbc:h2:mem:testdb url.

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_USER=petclinic -e MYSQL_PASSWORD=petclinic -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=petclinic -p 3306:3306 mysql:5.7.8

Further documentation is provided here.

Working with Petclinic in your IDE

Prerequisites

The following items should be installed in your system:

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. 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 in your browser.

Looking for something in particular?

Spring Boot Configuration Class or Java property files
The Main Class PetClinicApplication
Properties Files application.properties
Caching CacheConfiguration

Interesting Spring Petclinic branches and forks

The Spring Petclinic "main" branch in the spring-projects GitHub org is the "canonical" implementation, currently based on Spring Boot and Thymeleaf. There are quite a few forks in a special GitHub org 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 and SPR-10257
Bean Validation / Hibernate Validator: simplify Maven dependencies and backward compatibility HV-790 and HV-792
Spring Data: provide more flexibility when working with JPQL queries DATAJPA-292

Contributing

The issue tracker is the preferred channel for bug reports, features requests and submitting pull requests.

For pull requests, editor preferences are available in the editor config 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.

License

The Spring PetClinic sample application is released under version 2.0 of the Apache License.

Comments
  • fix comment about the cache size and clarify configuration

    fix comment about the cache size and clarify configuration

    The comment Create a cache using infinite heap. is wrong. The JCache standard only requires a cache to store at least "some" values to pass the TCK. It is not required to be heap or infinite. cache2k limits to 2000 entries by default and passes the TCK.

    opened by cruftex 13
  • Add Gradle support

    Add Gradle support

    Is there any chance that this project would be converted to the Gradle build system? Seems like Gradle is the future and it would really come in handy to see how such a project would utilize it.

    I tried converting it but as this is the first real spring project I've dealt with, I cant wrap my head around all the configuration files :)

    question 
    opened by ghost 13
  • Bad example of N+1 in current implementation

    Bad example of N+1 in current implementation

    This implementation here should be improved by not fetching single items at a time:

    for (JdbcPet pet : pets) {
        owner.addPet(pet);
        pet.setType(EntityUtils.getById(getPetTypes(), PetType.class, pet.getTypeId()));
        List<Visit> visits = this.visitRepository.findByPetId(pet.getId()); // Problematic call
        for (Visit visit : visits) {
            pet.addVisit(visit);
        }
    }
    

    I'm not 100% convinced that the JDBC implementation of the pet clinic is very sensible in general. With SQL, I might be doing things a bit differently from JPA. It looks as though the whole example has been shoehorned into some pre-existing repositories.

    But anyway, this one should be a no-brainer. There should be a method like:

    interface VisitRepository {
        Map<Integer, List<Visit>> findByPetIds(Integer... ids);
    }
    
    opened by lukaseder 13
  • Modularize and migrate to aggregate-oriented domain

    Modularize and migrate to aggregate-oriented domain

    Vet, Owner, Visit. The Visit "aggregate" is a little artificial but it demonstrates a useful point about not holding on to references of "parent" (reference data) objects, i.e. the Visit has an Integer petId, instead of a Pet field. In principle this app is now almost ready to migrate to multiple services if anyone wanted to do that.

    opened by dsyer 12
  • Why do you have to add pet to owner after you find pet by id?

    Why do you have to add pet to owner after you find pet by id?

    I am not sure if you have to addPet() to owner again, after you find the pet for that owner using owner's ID.

    Owner owner = this.ownerRepository.findById(pet.getOwnerId());
    owner.addPet(pet);
    @Override
        public Pet findById(int id) throws DataAccessException {
            JdbcPet pet;
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", id);
                pet = this.namedParameterJdbcTemplate.queryForObject(
                    "SELECT id, name, birth_date, type_id, owner_id FROM pets WHERE id=:id",
                    params,
                    new JdbcPetRowMapper());
            } catch (EmptyResultDataAccessException ex) {
                throw new ObjectRetrievalFailureException(Pet.class, id);
            }
            Owner owner = this.ownerRepository.findById(pet.getOwnerId());
            owner.addPet(pet);
            pet.setType(EntityUtils.getById(findPetTypes(), PetType.class, pet.getTypeId()));
            List<Visit> visits = this.visitRepository.findByPetId(pet.getId());
            for (Visit visit : visits) {
                pet.addVisit(visit);
            }
            return pet;
        }
    
    enhancement question 
    opened by aagarw33 12
  • mvn tomcat7:run fails

    mvn tomcat7:run fails

    cpepool6cmts1-62:SpringExamples earlbingham$ mvn tomcat7:run [INFO] Scanning for projects... Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml Downloaded: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml (12 KB at 110.0 KB/sec) Downloaded: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml (22 KB at 170.1 KB/sec) [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.552s [INFO] Finished at: Wed Aug 07 21:00:47 PDT 2013 [INFO] Final Memory: 3M/81M [INFO] ------------------------------------------------------------------------ [ERROR] No plugin found for prefix 'tomcat7' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/earlbingham/.m2/repository), central (http://repo1.maven.org/maven2)] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException

    opened by earlbingham 10
  • Improved execution of grouped assertions

    Improved execution of grouped assertions

    Problem: A test method with many individual assertions stops being executed on the first failed assertion, which prevents the remaining ones' execution.

    Solution: Using AssertJ soft assertions feature, all assertions are executed, and all failures will be reported together. In this refactoring, no original assertion was changed.

    Result: Before:

    assertThat(owner.getLastName()).startsWith("Franklin");
    assertThat(owner.getPets()).hasSize(1);
    assertThat(owner.getPets().get(0).getType()).isNotNull();
    assertThat(owner.getPets().get(0).getType().getName()).isEqualTo("cat");
    

    After:

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(owner.getLastName()).startsWith("Franklin");
    softly.assertThat(owner.getPets()).hasSize(1);
    softly.assertThat(owner.getPets().get(0).getType()).isNotNull();
    softly.assertThat(owner.getPets().get(0).getType().getName()).isEqualTo("cat");
    softly.assertAll();
    
    opened by eas5 9
  • Jetty 9 support

    Jetty 9 support

    The Spring petlinic does not work on Jetty 9. The DandelionFilter throws an org.eclipse.jetty.io.EofException. I've open an issue on the Dandelion project: https://github.com/dandelion/dandelion/issues/113 Either we are waiting a fix or we replace Dandelion by another solution.

    bug 
    opened by arey 9
  • petclinic.css does not exist

    petclinic.css does not exist

    Hi there, the styling of the site displaying incorrectly, Chrome debug console shows that request for petclinic.css was failed with an error code of 404, and i looked through both my local and online repository, and I couldn't find the file in path "/resources/css/petclinic.css". Could you guys provide the css file please? Thanks. The Chrome debug console screenshot: a8be52db4fa6abc623f429c3235121e

    opened by guochengjun1993 8
  • Add support for Postgres

    Add support for Postgres

    in addition to h2, Petclinic app comes with support for mysql, it would be nice to have similar support for the second (maybe first ;-)) most popular open source database Postgres.

    Support can be done along the same lines as the one for mysql, namely to add the following files and folders:

    • resources/
      • application-postgres.properties
      • db/
        • postgres/
          • data.sql
          • schema.sql

    And finally, posgres jdbc driver should be added to the runtime dependencies in pom.xml

    I have also attached to this issue all of the above files, for review.

    resources.zip schema.sql

    opened by dmadunic 8
  • Fix content negotiation for /vets

    Fix content negotiation for /vets

    opened by aidenchiavatti 7
  • Getting error while following the steps

    Getting error while following the steps

    When I run ./mvnw package I get this:

    Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.maven.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:39) at org.apache.maven.wrapper.WrapperExecutor.execute(WrapperExecutor.java:122) at org.apache.maven.wrapper.MavenWrapperMain.main(MavenWrapperMain.java:61) Caused by: java.lang.NoClassDefFoundError: org/apache/commons/cli/UnrecognizedOptionException at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) at java.lang.Class.privateGetMethodRecursive(Class.java:3048) at java.lang.Class.getMethod0(Class.java:3018) at java.lang.Class.getMethod(Class.java:1784) at org.codehaus.plexus.classworlds.launcher.Launcher.getEnhancedMainMethod(Launcher.java:168) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:261) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347) ... 7 more Caused by: java.lang.ClassNotFoundException: org.apache.commons.cli.UnrecognizedOptionException at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50) at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239) ... 17 more

    opened by ramkis1 0
  • Wrong clone link in readme

    Wrong clone link in readme

    https://github.com/PebbleTemplates/spring-petclinic/blob/master/readme.md?plain=1#L13 The link to clone the project is not correct. It should be https://github.com/PebbleTemplates/spring-petclinic.git

    opened by adoykov 0
Owner
Spring
Spring
Demonstrates the features of the Spring MVC web framework

Spring MVC Showcase Demonstrates the capabilities of the Spring MVC web framework through small, simple examples. After reviewing this showcase, you s

Spring 5k Jan 5, 2023
Spring Data Example Projects

Spring Data Examples This repository contains example projects for the different Spring Data modules to showcase the API and how to use the features p

Spring 4.7k Jan 4, 2023
循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Batch、Spring Cloud、Spring Cloud Alibaba、Spring Security & Spring Security OAuth2,博客Spring系列源码:https://mrbird.cc

Spring 系列教程 该仓库为个人博客https://mrbird.cc中Spring系列源码,包含Spring Boot、Spring Boot & Shiro、Spring Cloud,Spring Boot & Spring Security & Spring Security OAuth2

mrbird 24.8k Jan 6, 2023
Sample application demonstrating an order fulfillment system decomposed into multiple independant components (e.g. microservices). Showing concrete implementation alternatives using e.g. Java, Spring Boot, Apache Kafka, Camunda, Zeebe, ...

Sample application demonstrating an order fulfillment system decomposed into multiple independant components (e.g. microservices). Showing concrete implementation alternatives using e.g. Java, Spring Boot, Apache Kafka, Camunda, Zeebe, ...

Bernd Ruecker 1.2k Dec 14, 2022
Sample Spring Boot CLI application

sb-cli Sample Spring Boot CLI application. Shows how a Spring Boot application may be configured and packaged to create native executables with GraalV

Andres Almiray 28 Nov 2, 2022
Sample Spring-Cloud-Api-Gateway Project of Spring Boot

Sample-Spring-Cloud-Api-Gateway Sample Spring-Cloud-Api-Gateway Project of Spring Boot Proejct Stack Spring Webflux Spring Cloud Gateway Spring Data R

Seokhyun 2 Jan 17, 2022
The Spring Boot Sample App on K8S has been implemented using GKE K8S Cluster, Spring Boot, Maven, and Docker.

gke-springboot-sampleapp ?? The Spring Boot Sample App on K8S has been implemented using GKE K8S Cluster, Spring Boot, Maven, and Docker. Usage To be

KYEONGMIN CHO 1 Feb 1, 2022
Sample serverless application written in Java compiled with GraalVM native-image

Serverless GraalVM Demo This is a simple serverless application built in Java and uses the GraalVM native-image tool. It consists of an Amazon API Gat

AWS Samples 143 Dec 22, 2022
Log4Shell sample vulnerable application (CVE-2021-44228)

Log4Shell sample vulnerable application (CVE-2021-44228)

StandB 5 Dec 26, 2021
This is a sample application demonstrating Quarkus features and best practices

Quarkus Superheroes Sample Table of Contents Introduction Project automation GitHub action automation Application Resource Generation Running Locally

QuarkusIO 123 Jan 6, 2023
A sample eForms application that can visualise an eForms notice

A sample eForms application that can visualise an eForms notice. It uses efx-translator-java to generate XSL templates from notice view templates written in EFX. It then uses an XSLT processor to generate an HTML visualisation of any given eForms notice.

TED & EU Public Procurement 6 Nov 23, 2022
该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的线上博客项目/企业大型商城系统/前后端分离实践项目等,摆脱各种 hello world 入门案例的束缚,真正的掌握 Spring Boot 开发。

Spring Boot Projects 该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的前

十三 4.5k Dec 30, 2022
You are looking for examples, code snippets, sample applications for Spring Integration? This is the place.

Spring Integration Samples Note This (master) branch requires Spring Integration 5.0 or above. For samples running against earlier versions of Spring

Spring 2.1k Dec 30, 2022
A sample microservice built with Spring Boot and Gradle.

Project Overview A sample microservice built with Spring Boot and Gradle. There are APIs built using REST and the resource is bicycle. All CRUD operat

Gordon Mendonsa 1 Feb 2, 2022
An implementation of a sample E-Commerce app in k8s. This online retail marketplace app uses Spring Boot, React, and YugabyteDB.

An implementation of a sample E-Commerce app in k8s. This online retail marketplace app uses Spring Boot, React, and YugabyteDB.

yugabyte 1 Oct 27, 2022
Bank Statement Analyzer Application that currently runs in terminal with the commands: javac Application.java java Application [file-name].csv GUI coming soon...

Bank Statement Analyzer Application that currently runs in terminal with the commands: javac Application.java java Application [file-name].csv GUI coming soon...

Hayden Hanson 0 May 21, 2022
Two Spring-boot applications registering themselves to an spring-boot-admin-server application as separate clients for the purpose of monitoring and managing the clients

Spring-boot-admin implementation with 1 Server and 2 clients Creating a Server application to monitor and manage Spring boot applications (clients) un

null 6 Dec 6, 2022
Kafka-spring-boot-starter: encapsulated based on spring-kafka

Encapsulation based on spring-kafka not only supports native configuration, but also adds multi data source configuration.

liudong 8 Jan 9, 2023