diff --git a/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java b/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java index 9770ef7bece1eca1c2f96f2ea110b20ea406adc3..8dfbfe90b4310b667c83b9d38e6e3619970b2218 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java +++ b/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java @@ -21,28 +21,28 @@ import javax.persistence.Id; import javax.persistence.MappedSuperclass; /** - * Simple JavaBean domain object with an id property. - * Used as a base class for objects needing this property. + * Simple JavaBean domain object with an id property. Used as a base class for objects needing this property. * * @author Ken Krebs * @author Juergen Hoeller */ @MappedSuperclass public class BaseEntity { - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - protected Integer id; - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Integer id; - public void setId(Integer id) { - this.id = id; - } - public Integer getId() { - return id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean isNew() { - return (this.id == null); - } + public Integer getId() { + return id; + } + + public boolean isNew() { + return (this.id == null); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java b/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java index a5064eb936e2bdb5053c9ece77227b13c6bdc49d..cb36a6267a88372a99982fe1e6e566415f6e41ca 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java +++ b/src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java @@ -20,8 +20,8 @@ import javax.persistence.MappedSuperclass; /** - * Simple JavaBean domain object adds a name property to <code>BaseEntity</code>. - * Used as a base class for objects needing these properties. + * 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 @@ -29,21 +29,21 @@ import javax.persistence.MappedSuperclass; @MappedSuperclass public class NamedEntity extends BaseEntity { - @Column(name="name") - private String name; - + @Column(name = "name") + private String name; - public void setName(String name) { - this.name = name; - } - public String getName() { - return this.name; - } + public void setName(String name) { + this.name = name; + } - @Override - public String toString() { - return this.getName(); - } + public String getName() { + return this.name; + } + + @Override + public String toString() { + return this.getName(); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Owner.java b/src/main/java/org/springframework/samples/petclinic/model/Owner.java index 7b4d90b3f3b7be900094a4e041a327b60ac2e8ca..c0efd4670f5fcf1561cba85b7df46053bebaaa26 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Owner.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Owner.java @@ -15,24 +15,15 @@ */ package org.springframework.samples.petclinic.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.validation.constraints.Digits; - import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.support.MutableSortDefinition; import org.springframework.beans.support.PropertyComparator; import org.springframework.core.style.ToStringCreator; +import javax.persistence.*; +import javax.validation.constraints.Digits; +import java.util.*; + /** * Simple JavaBean domain object representing an owner. * @@ -41,111 +32,113 @@ import org.springframework.core.style.ToStringCreator; * @author Sam Brannen * @author Michael Isvy */ -@Entity @Table(name="owners") +@Entity +@Table(name = "owners") public class Owner extends Person { - @Column(name="address") - @NotEmpty - private String address; - - @Column(name="city") - @NotEmpty - private String city; - - @Column(name="telephone") - @NotEmpty @Digits(fraction = 0, integer = 10) - private String telephone; - - @OneToMany(cascade=CascadeType.ALL, mappedBy="owner") - 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(); - } + @Column(name = "address") + @NotEmpty + private String address; + + @Column(name = "city") + @NotEmpty + private String city; + + @Column(name = "telephone") + @NotEmpty + @Digits(fraction = 0, integer = 10) + private String telephone; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner") + 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(); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Person.java b/src/main/java/org/springframework/samples/petclinic/model/Person.java index 97f1edbc54da2e1d87dcc5716187193ed8990057..5e8655d920741d24bb026ccf3b8916a7449ae737 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Person.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Person.java @@ -15,11 +15,11 @@ */ package org.springframework.samples.petclinic.model; +import org.hibernate.validator.constraints.NotEmpty; + import javax.persistence.Column; import javax.persistence.MappedSuperclass; -import org.hibernate.validator.constraints.NotEmpty; - /** * Simple JavaBean domain object representing an person. * @@ -27,31 +27,30 @@ import org.hibernate.validator.constraints.NotEmpty; */ @MappedSuperclass public class Person extends BaseEntity { - - @Column(name="first_name") - @NotEmpty - protected String firstName; - @Column(name="last_name") - @NotEmpty - protected String lastName; + @Column(name = "first_name") + @NotEmpty + protected String firstName; - public String getFirstName() { - return this.firstName; - } + @Column(name = "last_name") + @NotEmpty + protected String lastName; - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public String getFirstName() { + return this.firstName; + } - public String getLastName() { - return this.lastName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public String getLastName() { + return this.lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Pet.java b/src/main/java/org/springframework/samples/petclinic/model/Pet.java index f5f279a03d2dd5b1624d5338ff378d9c424c1e52..5b3c806f9036411544feff523df782c91d91c137 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Pet.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Pet.java @@ -15,27 +15,15 @@ */ package org.springframework.samples.petclinic.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Table; - import org.hibernate.annotations.Type; import org.joda.time.DateTime; import org.springframework.beans.support.MutableSortDefinition; import org.springframework.beans.support.PropertyComparator; import org.springframework.format.annotation.DateTimeFormat; +import javax.persistence.*; +import java.util.*; + /** * Simple business object representing a pet. * @@ -43,70 +31,71 @@ import org.springframework.format.annotation.DateTimeFormat; * @author Juergen Hoeller * @author Sam Brannen */ -@Entity @Table(name="pets") +@Entity +@Table(name = "pets") public class Pet extends NamedEntity { - @Column(name="birth_date") - @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") - @DateTimeFormat(pattern="yyyy/MM/dd") - private DateTime birthDate; + @Column(name = "birth_date") + @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") + @DateTimeFormat(pattern = "yyyy/MM/dd") + private DateTime birthDate; - @ManyToOne + @ManyToOne @JoinColumn(name = "type_id") - private PetType type; - - @ManyToOne + private PetType type; + + @ManyToOne @JoinColumn(name = "owner_id") - private Owner owner; - - @OneToMany(cascade=CascadeType.ALL, mappedBy="pet", fetch=FetchType.EAGER) - private Set<Visit> visits; - - - public void setBirthDate(DateTime birthDate) { - this.birthDate = birthDate; - } - - public DateTime 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); - } + private Owner owner; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "pet", fetch = FetchType.EAGER) + private Set<Visit> visits; + + + public void setBirthDate(DateTime birthDate) { + this.birthDate = birthDate; + } + + public DateTime 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); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/PetType.java b/src/main/java/org/springframework/samples/petclinic/model/PetType.java index 8b3f1c0f61451f59a92e143eecffbc4ada5dc31e..50cf0399a7702ea2ec46da4c46626c935a045a5e 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/PetType.java +++ b/src/main/java/org/springframework/samples/petclinic/model/PetType.java @@ -21,7 +21,8 @@ import javax.persistence.Table; /** * @author Juergen Hoeller */ -@Entity @Table(name="types") +@Entity +@Table(name = "types") public class PetType extends NamedEntity { } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Specialty.java b/src/main/java/org/springframework/samples/petclinic/model/Specialty.java index 35724a8e35258f34cc7dfe14f9dce5b48fb65b92..6ea209cd45ac5fdaa287aabe9b3bfd7d71682102 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Specialty.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Specialty.java @@ -20,10 +20,11 @@ import javax.persistence.Table; /** * Models a {@link Vet Vet's} specialty (for example, dentistry). - * + * * @author Juergen Hoeller */ -@Entity @Table(name="specialties") +@Entity +@Table(name = "specialties") public class Specialty extends NamedEntity { } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Vet.java b/src/main/java/org/springframework/samples/petclinic/model/Vet.java index 328b8c3052f7d28741ab3507ddb486c5b9e4f854..4d767e0f35e6c071239f32c4769b9d1155ab1761 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Vet.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Vet.java @@ -15,23 +15,13 @@ */ package org.springframework.samples.petclinic.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlElement; - import org.springframework.beans.support.MutableSortDefinition; import org.springframework.beans.support.PropertyComparator; +import javax.persistence.*; +import javax.xml.bind.annotation.XmlElement; +import java.util.*; + /** * Simple JavaBean domain object representing a veterinarian. * @@ -40,39 +30,40 @@ import org.springframework.beans.support.PropertyComparator; * @author Sam Brannen * @author Arjen Poutsma */ -@Entity @Table(name="vets") +@Entity +@Table(name = "vets") public class Vet extends Person { - @ManyToMany(fetch=FetchType.EAGER) - @JoinTable (name="vet_specialties",joinColumns = @JoinColumn(name = "vet_id"), - inverseJoinColumns= @JoinColumn(name = "specialty_id")) - private Set<Specialty> specialties; + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "vet_specialties", joinColumns = @JoinColumn(name = "vet_id"), + inverseJoinColumns = @JoinColumn(name = "specialty_id")) + private Set<Specialty> specialties; - protected void setSpecialtiesInternal(Set<Specialty> specialties) { - this.specialties = 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; - } + 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); - } + @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 int getNrOfSpecialties() { + return getSpecialtiesInternal().size(); + } - public void addSpecialty(Specialty specialty) { - getSpecialtiesInternal().add(specialty); - } + public void addSpecialty(Specialty specialty) { + getSpecialtiesInternal().add(specialty); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Vets.java b/src/main/java/org/springframework/samples/petclinic/model/Vets.java index 6882eabe744363be52e1d912bf42e84ba7fcb6b4..48676e9a68ba974b900b8db3e4bf7c02d849f21b 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Vets.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Vets.java @@ -16,29 +16,28 @@ */ package org.springframework.samples.petclinic.model; -import java.util.ArrayList; -import java.util.List; - import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.List; /** - * Simple domain object representing a list of veterinarians. Mostly here to be used for the 'vets' - * {@link org.springframework.web.servlet.view.xml.MarshallingView}. + * Simple domain object representing a list of veterinarians. Mostly here to be used for the 'vets' {@link + * org.springframework.web.servlet.view.xml.MarshallingView}. * * @author Arjen Poutsma */ @XmlRootElement public class Vets { - private List<Vet> vets; + private List<Vet> vets; - @XmlElement - public List<Vet> getVetList() { - if (vets == null) { - vets = new ArrayList<Vet>(); - } - return vets; - } + @XmlElement + public List<Vet> getVetList() { + if (vets == null) { + vets = new ArrayList<Vet>(); + } + return vets; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/model/Visit.java b/src/main/java/org/springframework/samples/petclinic/model/Visit.java index 704021d201acfc5d18553d59fa072549113b4b73..9ea0897f86064758dd5a39b024c5c0e505874155 100644 --- a/src/main/java/org/springframework/samples/petclinic/model/Visit.java +++ b/src/main/java/org/springframework/samples/petclinic/model/Visit.java @@ -15,88 +15,105 @@ */ package org.springframework.samples.petclinic.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - import org.hibernate.annotations.Type; import org.hibernate.validator.constraints.NotEmpty; import org.joda.time.DateTime; import org.springframework.format.annotation.DateTimeFormat; +import javax.persistence.*; + /** * Simple JavaBean domain object representing a visit. * * @author Ken Krebs */ -@Entity @Table(name="visits") +@Entity +@Table(name = "visits") public class Visit extends BaseEntity { - /** Holds value of property date. */ - @Column(name="visit_date") - @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") - @DateTimeFormat(pattern="yyyy/MM/dd") - private DateTime date; - - /** Holds value of property description. */ - @NotEmpty - @Column(name="description") - private String description; - - /** Holds value of property pet. */ - @ManyToOne + /** + * Holds value of property date. + */ + @Column(name = "visit_date") + @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") + @DateTimeFormat(pattern = "yyyy/MM/dd") + private DateTime date; + + /** + * Holds value of property description. + */ + @NotEmpty + @Column(name = "description") + private String description; + + /** + * Holds value of property pet. + */ + @ManyToOne @JoinColumn(name = "pet_id") - private Pet pet; - - - /** Creates a new instance of Visit for the current date */ - public Visit() { - this.date = new DateTime(); - } - - - /** Getter for property date. - * @return Value of property date. - */ - public DateTime getDate() { - return this.date; - } - - /** Setter for property date. - * @param date New value of property date. - */ - public void setDate(DateTime 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; - } + private Pet pet; + + + /** + * Creates a new instance of Visit for the current date + */ + public Visit() { + this.date = new DateTime(); + } + + + /** + * Getter for property date. + * + * @return Value of property date. + */ + public DateTime getDate() { + return this.date; + } + + /** + * Setter for property date. + * + * @param date New value of property date. + */ + public void setDate(DateTime 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; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/OwnerRepository.java b/src/main/java/org/springframework/samples/petclinic/repository/OwnerRepository.java index 2046abe0eb4a0c3519c99bf197b1fbd977b2c0a3..e87aa5fbda2a165120c28c71b315ddf88ff3ee9f 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/OwnerRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/OwnerRepository.java @@ -30,49 +30,51 @@ */ package org.springframework.samples.petclinic.repository; -import java.util.Collection; - import org.springframework.dao.DataAccessException; import org.springframework.samples.petclinic.model.BaseEntity; import org.springframework.samples.petclinic.model.Owner; +import java.util.Collection; + /** - * Repository class for <code>Owner</code> domain objects - * All method names are compliant with Spring Data naming conventions so this interface can easily be - * extended for Spring Data - * See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation - * + * Repository class for <code>Owner</code> domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * * @author Ken Krebs * @author Juergen Hoeller * @author Sam Brannen * @author Michael Isvy - */ + */ public interface OwnerRepository { - /** - * 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> findByLastName(String lastName) 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> findByLastName(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 findById(int id) 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 findById(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 save(Owner owner) 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 save(Owner owner) throws DataAccessException; } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/PetRepository.java b/src/main/java/org/springframework/samples/petclinic/repository/PetRepository.java index 4cbd48d86c409b9e5492fd7442c7820a211d40cd..a075bc00ade20fc84f00b9b9aeea2c89a4970fe8 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/PetRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/PetRepository.java @@ -15,18 +15,16 @@ */ package org.springframework.samples.petclinic.repository; -import java.util.List; - import org.springframework.dao.DataAccessException; import org.springframework.samples.petclinic.model.BaseEntity; import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; +import java.util.List; + /** - * Repository class for <code>Pet</code> domain objects - * All method names are compliant with Spring Data naming conventions so this interface can easily be - * extended for Spring Data - * See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * Repository class for <code>Pet</code> domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation * * @author Ken Krebs * @author Juergen Hoeller @@ -35,25 +33,29 @@ import org.springframework.samples.petclinic.model.PetType; */ public interface PetRepository { - /** - * Retrieve all <code>PetType</code>s from the data store. - * @return a <code>Collection</code> of <code>PetType</code>s - */ - List<PetType> findPetTypes() throws DataAccessException; + /** + * Retrieve all <code>PetType</code>s from the data store. + * + * @return a <code>Collection</code> of <code>PetType</code>s + */ + List<PetType> findPetTypes() 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 findById(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 findById(int id) 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 save(Pet pet) 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 save(Pet pet) throws DataAccessException; } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/VetRepository.java b/src/main/java/org/springframework/samples/petclinic/repository/VetRepository.java index 183192e549b66627278e5c16d713daf665c9a6f7..44f504d3a7167734dfe5dcd2bd9634e8e6e34600 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/VetRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/VetRepository.java @@ -15,16 +15,14 @@ */ package org.springframework.samples.petclinic.repository; -import java.util.Collection; - import org.springframework.dao.DataAccessException; import org.springframework.samples.petclinic.model.Vet; +import java.util.Collection; + /** - * Repository class for <code>Vet</code> domain objects - * All method names are compliant with Spring Data naming conventions so this interface can easily be - * extended for Spring Data - * See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * Repository class for <code>Vet</code> domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation * * @author Ken Krebs * @author Juergen Hoeller @@ -33,11 +31,12 @@ import org.springframework.samples.petclinic.model.Vet; */ public interface VetRepository { - /** - * Retrieve all <code>Vet</code>s from the data store. - * @return a <code>Collection</code> of <code>Vet</code>s - */ - Collection<Vet> findAll() throws DataAccessException; + /** + * Retrieve all <code>Vet</code>s from the data store. + * + * @return a <code>Collection</code> of <code>Vet</code>s + */ + Collection<Vet> findAll() throws DataAccessException; } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/VisitRepository.java b/src/main/java/org/springframework/samples/petclinic/repository/VisitRepository.java index a78b10bc0be9f32577b4268dba0232857cba0644..760f2001dab8040c25e58155652cabeec93c23dc 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/VisitRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/VisitRepository.java @@ -15,17 +15,15 @@ */ package org.springframework.samples.petclinic.repository; -import java.util.List; - import org.springframework.dao.DataAccessException; import org.springframework.samples.petclinic.model.BaseEntity; import org.springframework.samples.petclinic.model.Visit; +import java.util.List; + /** - * Repository class for <code>Visit</code> domain objects - * All method names are compliant with Spring Data naming conventions so this interface can easily be - * extended for Spring Data - * See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation + * Repository class for <code>Visit</code> domain objects All method names are compliant with Spring Data naming + * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation * * @author Ken Krebs * @author Juergen Hoeller @@ -34,13 +32,14 @@ import org.springframework.samples.petclinic.model.Visit; */ public interface VisitRepository { - /** - * 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 save(Visit visit) 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 save(Visit visit) throws DataAccessException; - List<Visit> findByPetId(Integer petId); + List<Visit> findByPetId(Integer petId); } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImpl.java index d186bb9497092412e26be3d2b5a98e60899fb2c5..646378d6cdc30d1e61cdaa0ffd97a7af2e72e551 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImpl.java @@ -15,13 +15,6 @@ */ package org.springframework.samples.petclinic.repository.jdbc; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; @@ -39,10 +32,15 @@ import org.springframework.samples.petclinic.repository.VisitRepository; import org.springframework.samples.petclinic.util.EntityUtils; import org.springframework.stereotype.Repository; +import javax.sql.DataSource; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * A simple JDBC-based implementation of the {@link OwnerRepository} interface. * - * * @author Ken Krebs * @author Juergen Hoeller * @author Rob Harrop @@ -53,119 +51,115 @@ import org.springframework.stereotype.Repository; @Repository public class JdbcOwnerRepositoryImpl implements OwnerRepository { - private VisitRepository visitRepository; - - private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - - private SimpleJdbcInsert insertOwner; - - @Autowired - public JdbcOwnerRepositoryImpl(DataSource dataSource, NamedParameterJdbcTemplate namedParameterJdbcTemplate, - VisitRepository visitRepository) { - - this.insertOwner = new SimpleJdbcInsert(dataSource) - .withTableName("owners") - .usingGeneratedKeyColumns("id"); - - this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); - - this.visitRepository = visitRepository; - } - - - - - /** - * Loads {@link Owner Owners} from the data store by last name, returning - * all owners whose last name <i>starts</i> with the given name; also loads - * the {@link Pet Pets} and {@link Visit Visits} for the corresponding - * owners, if not already loaded. - */ - public Collection<Owner> findByLastName(String lastName) throws DataAccessException { - Map<String, Object> params = new HashMap<String, Object>(); - params.put("lastName", lastName+"%"); - List<Owner> owners = this.namedParameterJdbcTemplate.query( - "SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE last_name like :lastName", - params, - ParameterizedBeanPropertyRowMapper.newInstance(Owner.class) - ); - loadOwnersPetsAndVisits(owners); - return owners; - } - - /** - * Loads the {@link Owner} with the supplied <code>id</code>; also loads - * the {@link Pet Pets} and {@link Visit Visits} for the corresponding - * owner, if not already loaded. - */ - public Owner findById(int id) throws DataAccessException { - Owner owner; - try { - Map<String, Object> params = new HashMap<String, Object>(); - params.put("id", id); - owner = this.namedParameterJdbcTemplate.queryForObject( - "SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE id= :id", - params, - ParameterizedBeanPropertyRowMapper.newInstance(Owner.class) - ); - } - catch (EmptyResultDataAccessException ex) { - throw new ObjectRetrievalFailureException(Owner.class, new Integer(id)); - } - loadPetsAndVisits(owner); - return owner; - } - - public void loadPetsAndVisits(final Owner owner) { - Map<String, Object> params = new HashMap<String, Object>(); - params.put("id", owner.getId().intValue()); - final List<JdbcPet> pets = this.namedParameterJdbcTemplate.query( - "SELECT id, name, birth_date, type_id, owner_id FROM pets WHERE owner_id=:id", - params, - new JdbcPetRowMapper() - ); - for (JdbcPet pet : pets) { - owner.addPet(pet); - pet.setType(EntityUtils.getById(getPetTypes(), PetType.class, pet.getTypeId())); - List<Visit> visits = this.visitRepository.findByPetId(pet.getId()); - for (Visit visit : visits) { - pet.addVisit(visit); - } - } - } - - public void save(Owner owner) throws DataAccessException { - BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner); - if (owner.isNew()) { - Number newKey = this.insertOwner.executeAndReturnKey(parameterSource); - owner.setId(newKey.intValue()); - } - else { - this.namedParameterJdbcTemplate.update( - "UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " + - "city=:city, telephone=:telephone WHERE id=:id", - parameterSource); - } - } - - public Collection<PetType> getPetTypes() throws DataAccessException { - return this.namedParameterJdbcTemplate.query( - "SELECT id, name FROM types ORDER BY name", new HashMap<String,Object>(), - ParameterizedBeanPropertyRowMapper.newInstance(PetType.class)); - } - - /** - * Loads the {@link Pet} and {@link Visit} data for the supplied - * {@link List} of {@link Owner Owners}. - * - * @param owners the list of owners for whom the pet and visit data should be loaded - * @see #loadPetsAndVisits(Owner) - */ - private void loadOwnersPetsAndVisits(List<Owner> owners) { - for (Owner owner : owners) { - loadPetsAndVisits(owner); - } - } + private VisitRepository visitRepository; + + private NamedParameterJdbcTemplate namedParameterJdbcTemplate; + + private SimpleJdbcInsert insertOwner; + + @Autowired + public JdbcOwnerRepositoryImpl(DataSource dataSource, NamedParameterJdbcTemplate namedParameterJdbcTemplate, + VisitRepository visitRepository) { + + this.insertOwner = new SimpleJdbcInsert(dataSource) + .withTableName("owners") + .usingGeneratedKeyColumns("id"); + + this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + + this.visitRepository = visitRepository; + } + + + /** + * Loads {@link Owner Owners} from the data store by last name, returning all owners whose last name <i>starts</i> with + * the given name; also loads the {@link Pet Pets} and {@link Visit Visits} for the corresponding owners, if not + * already loaded. + */ + @Override + public Collection<Owner> findByLastName(String lastName) throws DataAccessException { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("lastName", lastName + "%"); + List<Owner> owners = this.namedParameterJdbcTemplate.query( + "SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE last_name like :lastName", + params, + ParameterizedBeanPropertyRowMapper.newInstance(Owner.class) + ); + loadOwnersPetsAndVisits(owners); + return owners; + } + + /** + * Loads the {@link Owner} with the supplied <code>id</code>; also loads the {@link Pet Pets} and {@link Visit Visits} + * for the corresponding owner, if not already loaded. + */ + @Override + public Owner findById(int id) throws DataAccessException { + Owner owner; + try { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("id", id); + owner = this.namedParameterJdbcTemplate.queryForObject( + "SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE id= :id", + params, + ParameterizedBeanPropertyRowMapper.newInstance(Owner.class) + ); + } catch (EmptyResultDataAccessException ex) { + throw new ObjectRetrievalFailureException(Owner.class, new Integer(id)); + } + loadPetsAndVisits(owner); + return owner; + } + + public void loadPetsAndVisits(final Owner owner) { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("id", owner.getId().intValue()); + final List<JdbcPet> pets = this.namedParameterJdbcTemplate.query( + "SELECT id, name, birth_date, type_id, owner_id FROM pets WHERE owner_id=:id", + params, + new JdbcPetRowMapper() + ); + for (JdbcPet pet : pets) { + owner.addPet(pet); + pet.setType(EntityUtils.getById(getPetTypes(), PetType.class, pet.getTypeId())); + List<Visit> visits = this.visitRepository.findByPetId(pet.getId()); + for (Visit visit : visits) { + pet.addVisit(visit); + } + } + } + + @Override + public void save(Owner owner) throws DataAccessException { + BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner); + if (owner.isNew()) { + Number newKey = this.insertOwner.executeAndReturnKey(parameterSource); + owner.setId(newKey.intValue()); + } else { + this.namedParameterJdbcTemplate.update( + "UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " + + "city=:city, telephone=:telephone WHERE id=:id", + parameterSource); + } + } + + public Collection<PetType> getPetTypes() throws DataAccessException { + return this.namedParameterJdbcTemplate.query( + "SELECT id, name FROM types ORDER BY name", new HashMap<String, Object>(), + ParameterizedBeanPropertyRowMapper.newInstance(PetType.class)); + } + + /** + * Loads the {@link Pet} and {@link Visit} data for the supplied {@link List} of {@link Owner Owners}. + * + * @param owners the list of owners for whom the pet and visit data should be loaded + * @see #loadPetsAndVisits(Owner) + */ + private void loadOwnersPetsAndVisits(List<Owner> owners) { + for (Owner owner : owners) { + loadPetsAndVisits(owner); + } + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPet.java b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPet.java index 25d93a3ca8f0437ec45699708bfb72c1a8d15ce1..b548629c76b899eea94d4e7c5493a292303c0fd1 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPet.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPet.java @@ -18,33 +18,33 @@ package org.springframework.samples.petclinic.repository.jdbc; import org.springframework.samples.petclinic.model.Pet; /** - * Subclass of Pet that carries temporary id properties which - * are only relevant for a JDBC implmentation of the ClinicService. + * Subclass of Pet that carries temporary id properties which are only relevant for a JDBC implmentation of the + * ClinicService. * * @author Juergen Hoeller * @see JdbcClinicImpl */ class JdbcPet extends Pet { - private int typeId; + private int typeId; - private int ownerId; + private int ownerId; - public void setTypeId(int typeId) { - this.typeId = typeId; - } + public void setTypeId(int typeId) { + this.typeId = typeId; + } - public int getTypeId() { - return this.typeId; - } + public int getTypeId() { + return this.typeId; + } - public void setOwnerId(int ownerId) { - this.ownerId = ownerId; - } + public void setOwnerId(int ownerId) { + this.ownerId = ownerId; + } - public int getOwnerId() { - return this.ownerId; - } + public int getOwnerId() { + return this.ownerId; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImpl.java index 693a77ea2876a0a60bf139d7bdeb302ceb3b9ccf..f11b5b05b9d62019ab035d26b381ff96c951cad3 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImpl.java @@ -15,12 +15,6 @@ */ package org.springframework.samples.petclinic.repository.jdbc; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; @@ -39,8 +33,12 @@ import org.springframework.samples.petclinic.repository.VisitRepository; import org.springframework.samples.petclinic.util.EntityUtils; import org.springframework.stereotype.Repository; +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** - * * @author Ken Krebs * @author Juergen Hoeller * @author Rob Harrop @@ -51,84 +49,84 @@ import org.springframework.stereotype.Repository; @Repository public class JdbcPetRepositoryImpl implements PetRepository { - private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - - private SimpleJdbcInsert insertPet; - - private OwnerRepository ownerRepository; - - private VisitRepository visitRepository; - - - @Autowired - public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository, VisitRepository visitRepository) { - this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); - - this.insertPet = new SimpleJdbcInsert(dataSource) - .withTableName("pets") - .usingGeneratedKeyColumns("id"); - - this.ownerRepository = ownerRepository; - this.visitRepository = visitRepository; - } - - public List<PetType> findPetTypes() throws DataAccessException { - Map<String, Object> params = new HashMap<String,Object>(); - return this.namedParameterJdbcTemplate.query( - "SELECT id, name FROM types ORDER BY name", - params, - ParameterizedBeanPropertyRowMapper.newInstance(PetType.class)); - } - - public Pet findById(int id) throws DataAccessException { - JdbcPet pet; - try { - Map<String, Object> params = new HashMap<String, Object>(); - 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, new Integer(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; - } - - public void save(Pet pet) throws DataAccessException { - if (pet.isNew()) { - Number newKey = this.insertPet.executeAndReturnKey( - createPetParameterSource(pet)); - pet.setId(newKey.intValue()); - } - else { - this.namedParameterJdbcTemplate.update( - "UPDATE pets SET name=:name, birth_date=:birth_date, type_id=:type_id, " + - "owner_id=:owner_id WHERE id=:id", - createPetParameterSource(pet)); - } - } - - /** - * Creates a {@link MapSqlParameterSource} based on data values from the - * supplied {@link Pet} instance. - */ - private MapSqlParameterSource createPetParameterSource(Pet pet) { - return new MapSqlParameterSource() - .addValue("id", pet.getId()) - .addValue("name", pet.getName()) - .addValue("birth_date", pet.getBirthDate().toDate()) - .addValue("type_id", pet.getType().getId()) - .addValue("owner_id", pet.getOwner().getId()); - } + private NamedParameterJdbcTemplate namedParameterJdbcTemplate; + + private SimpleJdbcInsert insertPet; + + private OwnerRepository ownerRepository; + + private VisitRepository visitRepository; + + + @Autowired + public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository, VisitRepository visitRepository) { + this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + + this.insertPet = new SimpleJdbcInsert(dataSource) + .withTableName("pets") + .usingGeneratedKeyColumns("id"); + + this.ownerRepository = ownerRepository; + this.visitRepository = visitRepository; + } + + @Override + public List<PetType> findPetTypes() throws DataAccessException { + Map<String, Object> params = new HashMap<String, Object>(); + return this.namedParameterJdbcTemplate.query( + "SELECT id, name FROM types ORDER BY name", + params, + ParameterizedBeanPropertyRowMapper.newInstance(PetType.class)); + } + + @Override + public Pet findById(int id) throws DataAccessException { + JdbcPet pet; + try { + Map<String, Object> params = new HashMap<String, Object>(); + 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, new Integer(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; + } + + @Override + public void save(Pet pet) throws DataAccessException { + if (pet.isNew()) { + Number newKey = this.insertPet.executeAndReturnKey( + createPetParameterSource(pet)); + pet.setId(newKey.intValue()); + } else { + this.namedParameterJdbcTemplate.update( + "UPDATE pets SET name=:name, birth_date=:birth_date, type_id=:type_id, " + + "owner_id=:owner_id WHERE id=:id", + createPetParameterSource(pet)); + } + } + + /** + * Creates a {@link MapSqlParameterSource} based on data values from the supplied {@link Pet} instance. + */ + private MapSqlParameterSource createPetParameterSource(Pet pet) { + return new MapSqlParameterSource() + .addValue("id", pet.getId()) + .addValue("name", pet.getName()) + .addValue("birth_date", pet.getBirthDate().toDate()) + .addValue("type_id", pet.getType().getId()) + .addValue("owner_id", pet.getOwner().getId()); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRowMapper.java b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRowMapper.java index f76c639cd7c98d5c0d5a4c8321b9ef9d373fd790..0193a86530478353946b8724cbf19f05b1d0a728 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRowMapper.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRowMapper.java @@ -15,27 +15,28 @@ */ package org.springframework.samples.petclinic.repository.jdbc; +import org.joda.time.DateTime; +import org.springframework.jdbc.core.simple.ParameterizedRowMapper; + import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; -import org.joda.time.DateTime; -import org.springframework.jdbc.core.simple.ParameterizedRowMapper; - /** - * {@link ParameterizedRowMapper} implementation mapping data from a - * {@link ResultSet} to the corresponding properties of the {@link JdbcPet} class. + * {@link ParameterizedRowMapper} implementation mapping data from a {@link ResultSet} to the corresponding properties + * of the {@link JdbcPet} class. */ class JdbcPetRowMapper implements ParameterizedRowMapper<JdbcPet> { - public JdbcPet mapRow(ResultSet rs, int rownum) throws SQLException { - JdbcPet pet = new JdbcPet(); - pet.setId(rs.getInt("id")); - pet.setName(rs.getString("name")); - Date birthDate = rs.getDate("birth_date"); - pet.setBirthDate(new DateTime(birthDate)); - pet.setTypeId(rs.getInt("type_id")); - pet.setOwnerId(rs.getInt("owner_id")); - return pet; - } + @Override + public JdbcPet mapRow(ResultSet rs, int rownum) throws SQLException { + JdbcPet pet = new JdbcPet(); + pet.setId(rs.getInt("id")); + pet.setName(rs.getString("name")); + Date birthDate = rs.getDate("birth_date"); + pet.setBirthDate(new DateTime(birthDate)); + pet.setTypeId(rs.getInt("type_id")); + pet.setOwnerId(rs.getInt("owner_id")); + return pet; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImpl.java index 0783bd52a3cdb97dbb197587953c990265daf751..a354c2a83f72647533f50946027eb9bfa713115e 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImpl.java @@ -15,12 +15,6 @@ */ package org.springframework.samples.petclinic.repository.jdbc; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.dao.DataAccessException; @@ -33,11 +27,16 @@ import org.springframework.samples.petclinic.repository.VetRepository; import org.springframework.samples.petclinic.util.EntityUtils; import org.springframework.stereotype.Repository; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + /** + * A simple JDBC-based implementation of the {@link VetRepository} interface. Uses @Cacheable to cache the result of the + * {@link findAll} method * - * A simple JDBC-based implementation of the {@link VetRepository} interface. - * Uses @Cacheable to cache the result of the {@link findAll} method - * * @author Ken Krebs * @author Juergen Hoeller * @author Rob Harrop @@ -49,44 +48,48 @@ import org.springframework.stereotype.Repository; @Repository public class JdbcVetRepositoryImpl implements VetRepository { - private JdbcTemplate jdbcTemplate; + private JdbcTemplate jdbcTemplate; - @Autowired - public JdbcVetRepositoryImpl(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } + @Autowired + public JdbcVetRepositoryImpl(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } - /** - * Refresh the cache of Vets that the ClinicService is holding. - * @see org.springframework.samples.petclinic.model.service.ClinicService#findVets() - */ - @Cacheable(value="vets") - public Collection<Vet> findAll() throws DataAccessException { - List<Vet> vets = new ArrayList<Vet>(); - // Retrieve the list of all vets. - vets.addAll(this.jdbcTemplate.query( - "SELECT id, first_name, last_name FROM vets ORDER BY last_name,first_name", - ParameterizedBeanPropertyRowMapper.newInstance(Vet.class))); + /** + * Refresh the cache of Vets that the ClinicService is holding. + * + * @see org.springframework.samples.petclinic.model.service.ClinicService#findVets() + */ + @Override + @Cacheable(value = "vets") + public Collection<Vet> findAll() throws DataAccessException { + List<Vet> vets = new ArrayList<Vet>(); + // Retrieve the list of all vets. + vets.addAll(this.jdbcTemplate.query( + "SELECT id, first_name, last_name FROM vets ORDER BY last_name,first_name", + ParameterizedBeanPropertyRowMapper.newInstance(Vet.class))); - // Retrieve the list of all possible specialties. - final List<Specialty> specialties = this.jdbcTemplate.query( - "SELECT id, name FROM specialties", - ParameterizedBeanPropertyRowMapper.newInstance(Specialty.class)); + // Retrieve the list of all possible specialties. + final List<Specialty> specialties = this.jdbcTemplate.query( + "SELECT id, name FROM specialties", + ParameterizedBeanPropertyRowMapper.newInstance(Specialty.class)); - // Build each vet's list of specialties. - for (Vet vet : vets) { - final List<Integer> vetSpecialtiesIds = this.jdbcTemplate.query( - "SELECT specialty_id FROM vet_specialties WHERE vet_id=?", - new ParameterizedRowMapper<Integer>() { - public Integer mapRow(ResultSet rs, int row) throws SQLException { - return Integer.valueOf(rs.getInt(1)); - }}, - vet.getId().intValue()); - for (int specialtyId : vetSpecialtiesIds) { - Specialty specialty = EntityUtils.getById(specialties, Specialty.class, specialtyId); - vet.addSpecialty(specialty); - } - } - return vets; - } + // Build each vet's list of specialties. + for (Vet vet : vets) { + final List<Integer> vetSpecialtiesIds = this.jdbcTemplate.query( + "SELECT specialty_id FROM vet_specialties WHERE vet_id=?", + new ParameterizedRowMapper<Integer>() { + @Override + public Integer mapRow(ResultSet rs, int row) throws SQLException { + return Integer.valueOf(rs.getInt(1)); + } + }, + vet.getId().intValue()); + for (int specialtyId : vetSpecialtiesIds) { + Specialty specialty = EntityUtils.getById(specialties, Specialty.class, specialtyId); + vet.addSpecialty(specialty); + } + } + return vets; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImpl.java index e0f6eb4225d33d48eee5dd52c9f3fb1531999e12..e8081aaef4d87bc11ae16184097c51e1b72a90da 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImpl.java @@ -15,13 +15,6 @@ */ package org.springframework.samples.petclinic.repository.jdbc; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Date; -import java.util.List; - -import javax.sql.DataSource; - import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; @@ -33,10 +26,15 @@ import org.springframework.samples.petclinic.model.Visit; import org.springframework.samples.petclinic.repository.VisitRepository; import org.springframework.stereotype.Repository; +import javax.sql.DataSource; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Date; +import java.util.List; + /** * A simple JDBC-based implementation of the {@link VisitRepository} interface. * - * * @author Ken Krebs * @author Juergen Hoeller * @author Rob Harrop @@ -48,63 +46,64 @@ import org.springframework.stereotype.Repository; @Repository public class JdbcVisitRepositoryImpl implements VisitRepository { - private JdbcTemplate jdbcTemplate; + private JdbcTemplate jdbcTemplate; - private SimpleJdbcInsert insertVisit; + private SimpleJdbcInsert insertVisit; - @Autowired - public JdbcVisitRepositoryImpl(DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); + @Autowired + public JdbcVisitRepositoryImpl(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); - this.insertVisit = new SimpleJdbcInsert(dataSource) - .withTableName("visits") - .usingGeneratedKeyColumns("id"); - } + this.insertVisit = new SimpleJdbcInsert(dataSource) + .withTableName("visits") + .usingGeneratedKeyColumns("id"); + } - public void save(Visit visit) throws DataAccessException { - if (visit.isNew()) { - Number newKey = this.insertVisit.executeAndReturnKey( - createVisitParameterSource(visit)); - visit.setId(newKey.intValue()); - } - else { - throw new UnsupportedOperationException("Visit update not supported"); - } - } + @Override + public void save(Visit visit) throws DataAccessException { + if (visit.isNew()) { + Number newKey = this.insertVisit.executeAndReturnKey( + createVisitParameterSource(visit)); + visit.setId(newKey.intValue()); + } else { + throw new UnsupportedOperationException("Visit update not supported"); + } + } - public void deletePet(int id) throws DataAccessException { - this.jdbcTemplate.update("DELETE FROM pets WHERE id=?", id); - } + public void deletePet(int id) throws DataAccessException { + this.jdbcTemplate.update("DELETE FROM pets WHERE id=?", id); + } - /** - * Creates a {@link MapSqlParameterSource} based on data values from the - * supplied {@link Visit} instance. - */ - private MapSqlParameterSource createVisitParameterSource(Visit visit) { - return new MapSqlParameterSource() - .addValue("id", visit.getId()) - .addValue("visit_date", visit.getDate().toDate()) - .addValue("description", visit.getDescription()) - .addValue("pet_id", visit.getPet().getId()); - } + /** + * Creates a {@link MapSqlParameterSource} based on data values from the supplied {@link Visit} instance. + */ + private MapSqlParameterSource createVisitParameterSource(Visit visit) { + return new MapSqlParameterSource() + .addValue("id", visit.getId()) + .addValue("visit_date", visit.getDate().toDate()) + .addValue("description", visit.getDescription()) + .addValue("pet_id", visit.getPet().getId()); + } - public List<Visit> findByPetId(Integer petId) { - final List<Visit> visits = this.jdbcTemplate.query( - "SELECT id, visit_date, description FROM visits WHERE pet_id=?", - new ParameterizedRowMapper<Visit>() { - public Visit mapRow(ResultSet rs, int row) throws SQLException { - Visit visit = new Visit(); - visit.setId(rs.getInt("id")); - Date visitDate = rs.getDate("visit_date"); - visit.setDate(new DateTime(visitDate)); - visit.setDescription(rs.getString("description")); - return visit; - } - }, - petId); - return visits; - } + @Override + public List<Visit> findByPetId(Integer petId) { + final List<Visit> visits = this.jdbcTemplate.query( + "SELECT id, visit_date, description FROM visits WHERE pet_id=?", + new ParameterizedRowMapper<Visit>() { + @Override + public Visit mapRow(ResultSet rs, int row) throws SQLException { + Visit visit = new Visit(); + visit.setId(rs.getInt("id")); + Date visitDate = rs.getDate("visit_date"); + visit.setDate(new DateTime(visitDate)); + visit.setDescription(rs.getString("description")); + return visit; + } + }, + petId); + return visits; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImpl.java index 898998056e6292a1b5f10356133e7be49f8422d0..3b85bfd8d350ed7249465de3e21033db7454a2a9 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImpl.java @@ -15,15 +15,14 @@ */ package org.springframework.samples.petclinic.repository.jpa; -import java.util.Collection; +import org.springframework.samples.petclinic.model.Owner; +import org.springframework.samples.petclinic.repository.OwnerRepository; +import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; - -import org.springframework.samples.petclinic.model.Owner; -import org.springframework.samples.petclinic.repository.OwnerRepository; -import org.springframework.stereotype.Repository; +import java.util.Collection; /** * JPA implementation of the {@link OwnerRepository} interface. @@ -37,31 +36,34 @@ import org.springframework.stereotype.Repository; @Repository public class JpaOwnerRepositoryImpl implements OwnerRepository { - @PersistenceContext - private EntityManager em; - + @PersistenceContext + private EntityManager em; + - @SuppressWarnings("unchecked") - public Collection<Owner> findByLastName(String lastName) { - // using 'join fetch' because a single query should load both owners and pets - // using 'left join fetch' because it might happen that an owner does not have pets yet - Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName"); - query.setParameter("lastName", lastName + "%"); - return query.getResultList(); - } + @Override + @SuppressWarnings("unchecked") + public Collection<Owner> findByLastName(String lastName) { + // using 'join fetch' because a single query should load both owners and pets + // using 'left join fetch' because it might happen that an owner does not have pets yet + Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName"); + query.setParameter("lastName", lastName + "%"); + return query.getResultList(); + } - public Owner findById(int id) { - // using 'join fetch' because a single query should load both owners and pets - // using 'left join fetch' because it might happen that an owner does not have pets yet - Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id"); - query.setParameter("id", id); - return (Owner) query.getSingleResult(); - } + @Override + public Owner findById(int id) { + // using 'join fetch' because a single query should load both owners and pets + // using 'left join fetch' because it might happen that an owner does not have pets yet + Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id"); + query.setParameter("id", id); + return (Owner) query.getSingleResult(); + } - public void save(Owner owner) { - this.em.merge(owner); + @Override + public void save(Owner owner) { + this.em.merge(owner); - } + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImpl.java index c83fd6966e50b12efa1a7e82908659b7b8bf339b..4073c9d863f84ac23d83e14eb4fd81ba94bcc3f5 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImpl.java @@ -15,16 +15,15 @@ */ package org.springframework.samples.petclinic.repository.jpa; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.repository.PetRepository; import org.springframework.stereotype.Repository; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.List; + /** * JPA implementation of the {@link PetRepository} interface. * @@ -37,20 +36,23 @@ import org.springframework.stereotype.Repository; @Repository public class JpaPetRepositoryImpl implements PetRepository { - @PersistenceContext - private EntityManager em; + @PersistenceContext + private EntityManager em; - @SuppressWarnings("unchecked") - public List<PetType> findPetTypes() { - return this.em.createQuery("SELECT ptype FROM PetType ptype ORDER BY ptype.name").getResultList(); - } + @Override + @SuppressWarnings("unchecked") + public List<PetType> findPetTypes() { + return this.em.createQuery("SELECT ptype FROM PetType ptype ORDER BY ptype.name").getResultList(); + } - public Pet findById(int id) { - return this.em.find(Pet.class, id); - } + @Override + public Pet findById(int id) { + return this.em.find(Pet.class, id); + } - public void save(Pet pet) { - this.em.merge(pet); - } + @Override + public void save(Pet pet) { + this.em.merge(pet); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImpl.java index b32abc7447aaf2394987386c00fe471f170025f1..5ab58d3ec86a894ae8ede2e79745fbaecc22890d 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImpl.java @@ -15,19 +15,18 @@ */ package org.springframework.samples.petclinic.repository.jpa; -import java.util.Collection; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - import org.springframework.cache.annotation.Cacheable; import org.springframework.samples.petclinic.model.Vet; import org.springframework.samples.petclinic.repository.VetRepository; import org.springframework.stereotype.Repository; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.Collection; + /** -* JPA implementation of the {@link VetRepository} interface. - * + * JPA implementation of the {@link VetRepository} interface. + * * @author Mike Keith * @author Rod Johnson * @author Sam Brannen @@ -37,14 +36,15 @@ import org.springframework.stereotype.Repository; @Repository public class JpaVetRepositoryImpl implements VetRepository { - @PersistenceContext - private EntityManager em; + @PersistenceContext + private EntityManager em; - @Cacheable(value="vets") - @SuppressWarnings("unchecked") - public Collection<Vet> findAll() { - return this.em.createQuery("SELECT vet FROM Vet vet join fetch vet.specialties ORDER BY vet.lastName, vet.firstName").getResultList(); - } + @Override + @Cacheable(value = "vets") + @SuppressWarnings("unchecked") + public Collection<Vet> findAll() { + return this.em.createQuery("SELECT vet FROM Vet vet join fetch vet.specialties ORDER BY vet.lastName, vet.firstName").getResultList(); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImpl.java index 3500a437fbe8f97781a84e697a9e96431bfd82b5..e9fbf07a867c17d929fff0556cc0cd0d6cbd65f9 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImpl.java @@ -15,19 +15,18 @@ */ package org.springframework.samples.petclinic.repository.jpa; -import java.util.List; +import org.springframework.samples.petclinic.model.Visit; +import org.springframework.samples.petclinic.repository.VisitRepository; +import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; - -import org.springframework.samples.petclinic.model.Visit; -import org.springframework.samples.petclinic.repository.VisitRepository; -import org.springframework.stereotype.Repository; +import java.util.List; /** * JPA implementation of the ClinicService interface using EntityManager. - * + * <p/> * <p>The mappings are defined in "orm.xml" located in the META-INF directory. * * @author Mike Keith @@ -39,20 +38,22 @@ import org.springframework.stereotype.Repository; @Repository public class JpaVisitRepositoryImpl implements VisitRepository { - @PersistenceContext - private EntityManager em; + @PersistenceContext + private EntityManager em; - public void save(Visit visit) { - this.em.merge(visit); - } + @Override + public void save(Visit visit) { + this.em.merge(visit); + } - @SuppressWarnings("unchecked") - public List<Visit> findByPetId(Integer petId) { - Query query = this.em.createQuery("SELECT visit FROM Visit v where v.pets.id= :id"); - query.setParameter("id", petId); - return query.getResultList(); - } + @Override + @SuppressWarnings("unchecked") + public List<Visit> findByPetId(Integer petId) { + Query query = this.em.createQuery("SELECT visit FROM Visit v where v.pets.id= :id"); + query.setParameter("id", petId); + return query.getResultList(); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImpl.java b/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImpl.java index 6f28d798cc8d21b3249f30f6fc493ac00069c31d..e6d050e59919215fba431bf6da931a21cd0e2cfb 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImpl.java @@ -15,51 +15,53 @@ */ package org.springframework.samples.petclinic.repository.springdatajpa; -import java.util.Collection; +import org.springframework.samples.petclinic.model.Owner; +import org.springframework.samples.petclinic.repository.OwnerRepository; +import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; - -import org.springframework.samples.petclinic.model.Owner; -import org.springframework.samples.petclinic.repository.OwnerRepository; -import org.springframework.stereotype.Repository; +import java.util.Collection; /** - * Using native JPA instead of Spring Data JPA here because of this query: - * "SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName" - * See https://jira.springsource.org/browse/DATAJPA-292 for more details. + * Using native JPA instead of Spring Data JPA here because of this query: "SELECT owner FROM Owner owner left join + * fetch owner.pets WHERE owner.lastName LIKE :lastName" See https://jira.springsource.org/browse/DATAJPA-292 for more + * details. * * @author Michael Isvy */ @Repository public class JpaOwnerRepositoryImpl implements OwnerRepository { - @PersistenceContext - private EntityManager em; - + @PersistenceContext + private EntityManager em; + - @SuppressWarnings("unchecked") - public Collection<Owner> findByLastName(String lastName) { - // using 'join fetch' because a single query should load both owners and pets - // using 'left join fetch' because it might happen that an owner does not have pets yet - Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName"); - query.setParameter("lastName", lastName + "%"); - return query.getResultList(); - } + @Override + @SuppressWarnings("unchecked") + public Collection<Owner> findByLastName(String lastName) { + // using 'join fetch' because a single query should load both owners and pets + // using 'left join fetch' because it might happen that an owner does not have pets yet + Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName"); + query.setParameter("lastName", lastName + "%"); + return query.getResultList(); + } - public Owner findById(int id) { - // using 'join fetch' because a single query should load both owners and pets - // using 'left join fetch' because it might happen that an owner does not have pets yet - Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id"); - query.setParameter("id", id); - return (Owner) query.getSingleResult(); - } + @Override + public Owner findById(int id) { + // using 'join fetch' because a single query should load both owners and pets + // using 'left join fetch' because it might happen that an owner does not have pets yet + Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id"); + query.setParameter("id", id); + return (Owner) query.getSingleResult(); + } - public void save(Owner owner) { - this.em.merge(owner); + @Override + public void save(Owner owner) { + this.em.merge(owner); - } + } } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataPetRepository.java b/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataPetRepository.java index 4cdf1ac132960b89b18e72c0b7e14c4e45a95aef..e510facd9a102d04261a7ceecf12377c64f882a4 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataPetRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataPetRepository.java @@ -15,8 +15,6 @@ */ package org.springframework.samples.petclinic.repository.springdatajpa; -import java.util.List; - import org.springframework.dao.DataAccessException; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; @@ -24,6 +22,8 @@ import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.repository.PetRepository; +import java.util.List; + /** * Spring Data JPA specialization of the {@link PetRepository} interface * @@ -31,7 +31,8 @@ import org.springframework.samples.petclinic.repository.PetRepository; * @since 15.1.2013 */ public interface SpringDataPetRepository extends PetRepository, Repository<Pet, Integer> { - - @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") - List<PetType> findPetTypes() throws DataAccessException; + + @Override + @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name") + List<PetType> findPetTypes() throws DataAccessException; } diff --git a/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataVisitRepository.java b/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataVisitRepository.java index 93b0c2a1cc2fe3a315a60fc467664a72d206f2ba..84740224b7fa9fe997ab9ee5f24938f8f79014e8 100644 --- a/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataVisitRepository.java +++ b/src/main/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataVisitRepository.java @@ -18,7 +18,7 @@ package org.springframework.samples.petclinic.repository.springdatajpa; import org.springframework.data.repository.Repository; import org.springframework.samples.petclinic.model.Visit; import org.springframework.samples.petclinic.repository.VisitRepository; - + /** * Spring Data JPA specialization of the {@link VisitRepository} interface * diff --git a/src/main/java/org/springframework/samples/petclinic/service/ClinicService.java b/src/main/java/org/springframework/samples/petclinic/service/ClinicService.java index 17440fb1142a649609492134ed0064f0f5e998e4..0ea3d7f16d9931f5c56b25bc7a3d0d2c5ae25086 100644 --- a/src/main/java/org/springframework/samples/petclinic/service/ClinicService.java +++ b/src/main/java/org/springframework/samples/petclinic/service/ClinicService.java @@ -15,14 +15,10 @@ */ package org.springframework.samples.petclinic.service; -import java.util.Collection; - import org.springframework.dao.DataAccessException; -import org.springframework.samples.petclinic.model.Owner; -import org.springframework.samples.petclinic.model.Pet; -import org.springframework.samples.petclinic.model.PetType; -import org.springframework.samples.petclinic.model.Vet; -import org.springframework.samples.petclinic.model.Visit; +import org.springframework.samples.petclinic.model.*; + +import java.util.Collection; /** @@ -31,21 +27,21 @@ import org.springframework.samples.petclinic.model.Visit; * @author Michael Isvy */ public interface ClinicService { - - public Collection<PetType> findPetTypes() throws DataAccessException; - - public Owner findOwnerById(int id) throws DataAccessException; - - public Pet findPetById(int id) throws DataAccessException; - public void savePet(Pet pet) throws DataAccessException; + public Collection<PetType> findPetTypes() throws DataAccessException; + + public Owner findOwnerById(int id) throws DataAccessException; + + public Pet findPetById(int id) throws DataAccessException; + + public void savePet(Pet pet) throws DataAccessException; + + public void saveVisit(Visit visit) throws DataAccessException; - public void saveVisit(Visit visit) throws DataAccessException; - - public Collection<Vet> findVets() throws DataAccessException; + public Collection<Vet> findVets() throws DataAccessException; - public void saveOwner(Owner owner) throws DataAccessException; + public void saveOwner(Owner owner) throws DataAccessException; - Collection<Owner> findOwnerByLastName(String lastName) throws DataAccessException; + Collection<Owner> findOwnerByLastName(String lastName) throws DataAccessException; } diff --git a/src/main/java/org/springframework/samples/petclinic/service/ClinicServiceImpl.java b/src/main/java/org/springframework/samples/petclinic/service/ClinicServiceImpl.java index eeb40371cadb5521ede3dd5ca9efdd8ba364d7b5..e03c1eb2cc744f16f95a171c2159578f4579b485 100644 --- a/src/main/java/org/springframework/samples/petclinic/service/ClinicServiceImpl.java +++ b/src/main/java/org/springframework/samples/petclinic/service/ClinicServiceImpl.java @@ -15,15 +15,9 @@ */ package org.springframework.samples.petclinic.service; -import java.util.Collection; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; -import org.springframework.samples.petclinic.model.Owner; -import org.springframework.samples.petclinic.model.Pet; -import org.springframework.samples.petclinic.model.PetType; -import org.springframework.samples.petclinic.model.Vet; -import org.springframework.samples.petclinic.model.Visit; +import org.springframework.samples.petclinic.model.*; import org.springframework.samples.petclinic.repository.OwnerRepository; import org.springframework.samples.petclinic.repository.PetRepository; import org.springframework.samples.petclinic.repository.VetRepository; @@ -31,6 +25,8 @@ import org.springframework.samples.petclinic.repository.VisitRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; + /** * Mostly used as a facade for all Petclinic controllers * @@ -38,70 +34,69 @@ import org.springframework.transaction.annotation.Transactional; */ @Service public class ClinicServiceImpl implements ClinicService { - - private PetRepository petRepository; - private VetRepository vetRepository; - private OwnerRepository ownerRepository; - private VisitRepository visitRepository; - - @Autowired - public ClinicServiceImpl(PetRepository petRepository, VetRepository vetRepository, OwnerRepository ownerRepository, VisitRepository visitRepository) { - this.petRepository = petRepository; - this.vetRepository = vetRepository; - this.ownerRepository = ownerRepository; - this.visitRepository = visitRepository; - } - - @Transactional(readOnly=true) - public Collection<PetType> findPetTypes() throws DataAccessException { - return petRepository.findPetTypes(); - } - - @Transactional(readOnly=true) - public Owner findOwnerById(int id) throws DataAccessException { - return ownerRepository.findById(id); - } - - @Transactional(readOnly=true) - public Collection<Owner> findOwnerByLastName(String lastName) throws DataAccessException { - return ownerRepository.findByLastName(lastName); - } - - @Transactional - public void saveOwner(Owner owner) throws DataAccessException { - ownerRepository.save(owner); - } - - - @Transactional - public void saveVisit(Visit visit) throws DataAccessException { - visitRepository.save(visit); - } - - - @Transactional(readOnly=true) - public Pet findPetById(int id) throws DataAccessException { - return petRepository.findById(id); - } - - @Transactional - public void savePet(Pet pet) throws DataAccessException { - petRepository.save(pet); - } - - @Transactional(readOnly=true) - public Collection<Vet> findVets() throws DataAccessException { - return vetRepository.findAll(); - } - - - - - - - - - - + + private PetRepository petRepository; + private VetRepository vetRepository; + private OwnerRepository ownerRepository; + private VisitRepository visitRepository; + + @Autowired + public ClinicServiceImpl(PetRepository petRepository, VetRepository vetRepository, OwnerRepository ownerRepository, VisitRepository visitRepository) { + this.petRepository = petRepository; + this.vetRepository = vetRepository; + this.ownerRepository = ownerRepository; + this.visitRepository = visitRepository; + } + + @Override + @Transactional(readOnly = true) + public Collection<PetType> findPetTypes() throws DataAccessException { + return petRepository.findPetTypes(); + } + + @Override + @Transactional(readOnly = true) + public Owner findOwnerById(int id) throws DataAccessException { + return ownerRepository.findById(id); + } + + @Override + @Transactional(readOnly = true) + public Collection<Owner> findOwnerByLastName(String lastName) throws DataAccessException { + return ownerRepository.findByLastName(lastName); + } + + @Override + @Transactional + public void saveOwner(Owner owner) throws DataAccessException { + ownerRepository.save(owner); + } + + + @Override + @Transactional + public void saveVisit(Visit visit) throws DataAccessException { + visitRepository.save(visit); + } + + + @Override + @Transactional(readOnly = true) + public Pet findPetById(int id) throws DataAccessException { + return petRepository.findById(id); + } + + @Override + @Transactional + public void savePet(Pet pet) throws DataAccessException { + petRepository.save(pet); + } + + @Override + @Transactional(readOnly = true) + public Collection<Vet> findVets() throws DataAccessException { + return vetRepository.findAll(); + } + } diff --git a/src/main/java/org/springframework/samples/petclinic/util/CallMonitoringAspect.java b/src/main/java/org/springframework/samples/petclinic/util/CallMonitoringAspect.java index 116e7f7aa0d4df14baca633db3141f2ab84cccd7..cad19ede0e5d8cd94d999dcd81e0ffb5eef33bfb 100644 --- a/src/main/java/org/springframework/samples/petclinic/util/CallMonitoringAspect.java +++ b/src/main/java/org/springframework/samples/petclinic/util/CallMonitoringAspect.java @@ -24,8 +24,8 @@ import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.util.StopWatch; /** - * Simple aspect that monitors call count and call invocation time. - * It uses JMX annotations and therefore can be monitored using any JMX console such as the jConsole + * Simple aspect that monitors call count and call invocation time. It uses JMX annotations and therefore can be + * monitored using any JMX console such as the jConsole * * @author Rob Harrop * @author Juergen Hoeller @@ -36,61 +36,58 @@ import org.springframework.util.StopWatch; @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.Repository *)") - 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(); - } - } + 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.Repository *)") + 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(); + } + } } diff --git a/src/main/java/org/springframework/samples/petclinic/util/EntityUtils.java b/src/main/java/org/springframework/samples/petclinic/util/EntityUtils.java index 822fed9b1f4dbcf90af60ee6173f0b703e08e9df..5e538bdca0da046309b283e09b5bcdcac4a3ec88 100644 --- a/src/main/java/org/springframework/samples/petclinic/util/EntityUtils.java +++ b/src/main/java/org/springframework/samples/petclinic/util/EntityUtils.java @@ -16,41 +16,40 @@ package org.springframework.samples.petclinic.util; -import java.util.Collection; - import org.springframework.orm.ObjectRetrievalFailureException; import org.springframework.samples.petclinic.model.BaseEntity; +import java.util.Collection; + /** - * Utility methods for handling entities. Separate from the BaseEntity class - * mainly because of dependency on the ORM-associated - * ObjectRetrievalFailureException. + * Utility methods for handling entities. Separate from the BaseEntity class mainly because of dependency on the + * ORM-associated ObjectRetrievalFailureException. * * @author Juergen Hoeller * @author Sam Brannen - * @since 29.10.2003 * @see org.springframework.samples.petclinic.model.BaseEntity + * @since 29.10.2003 */ public abstract class EntityUtils { - /** - * Look up the entity of the given class with the given id in the given - * collection. - * - * @param entities the collection to search - * @param entityClass the entity class to look up - * @param entityId the entity id to look up - * @return the found entity - * @throws ObjectRetrievalFailureException if the entity was not found - */ - public static <T extends BaseEntity> T getById(Collection<T> entities, Class<T> entityClass, int entityId) - throws ObjectRetrievalFailureException { - for (T entity : entities) { - if (entity.getId().intValue() == entityId && entityClass.isInstance(entity)) { - return entity; - } - } - throw new ObjectRetrievalFailureException(entityClass, new Integer(entityId)); - } + /** + * Look up the entity of the given class with the given id in the given collection. + * + * @param entities the collection to search + * @param entityClass the entity class to look up + * @param entityId the entity id to look up + * @return the found entity + * @throws ObjectRetrievalFailureException + * if the entity was not found + */ + public static <T extends BaseEntity> T getById(Collection<T> entities, Class<T> entityClass, int entityId) + throws ObjectRetrievalFailureException { + for (T entity : entities) { + if (entity.getId().intValue() == entityId && entityClass.isInstance(entity)) { + return entity; + } + } + throw new ObjectRetrievalFailureException(entityClass, new Integer(entityId)); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/web/CrashController.java b/src/main/java/org/springframework/samples/petclinic/web/CrashController.java index 6575b71daf6c5c3ab57c352082194517c06c2454..e413f3f3b8c73c3ed4931447dc123d419ab998c6 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/CrashController.java +++ b/src/main/java/org/springframework/samples/petclinic/web/CrashController.java @@ -21,20 +21,20 @@ import org.springframework.web.bind.annotation.RequestMethod; /** * Controller used to showcase what happens when an exception is thrown - * + * * @author Michael Isvy - * - * Also see how the bean of type 'SimpleMappingExceptionResolver' has been declared inside /WEB-INF/mvc-core-config.xml + * <p/> + * Also see how the bean of type 'SimpleMappingExceptionResolver' has been declared inside + * /WEB-INF/mvc-core-config.xml */ @Controller -public class CrashController { +public class CrashController { - @RequestMapping(value="/oups", method = RequestMethod.GET) - public String triggerException() { - throw new RuntimeException("Expected: controller used to showcase what " + - "happens when an exception is thrown"); - } + @RequestMapping(value = "/oups", method = RequestMethod.GET) + public String triggerException() { + throw new RuntimeException("Expected: controller used to showcase what " + + "happens when an exception is thrown"); + } - } diff --git a/src/main/java/org/springframework/samples/petclinic/web/OwnerController.java b/src/main/java/org/springframework/samples/petclinic/web/OwnerController.java index 6edafdd3904cec5e8ec8c78e5bf42b9f0ab75569..b05ecbf86f926b1f5a01443f1afd5a1c9016a219 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/OwnerController.java +++ b/src/main/java/org/springframework/samples/petclinic/web/OwnerController.java @@ -15,10 +15,6 @@ */ package org.springframework.samples.petclinic.web; -import java.util.Collection; - -import javax.validation.Valid; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Owner; import org.springframework.samples.petclinic.service.ClinicService; @@ -26,16 +22,14 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; +import javax.validation.Valid; +import java.util.Collection; + /** - * * @author Juergen Hoeller * @author Ken Krebs * @author Arjen Poutsma @@ -45,101 +39,98 @@ import org.springframework.web.servlet.ModelAndView; @SessionAttributes(types = Owner.class) public class OwnerController { - private final ClinicService clinicService; - - - @Autowired - public OwnerController(ClinicService clinicService) { - this.clinicService = clinicService; - } - - @InitBinder - public void setAllowedFields(WebDataBinder dataBinder) { - dataBinder.setDisallowedFields("id"); - } - - @RequestMapping(value="/owners/new", method = RequestMethod.GET) - public String initCreationForm(Model model) { - Owner owner = new Owner(); - model.addAttribute(owner); - return "owners/createOrUpdateOwnerForm"; - } - - @RequestMapping(value="/owners/new", method = RequestMethod.POST) - public String processCreationForm(@Valid Owner owner, BindingResult result, SessionStatus status) { - if (result.hasErrors()) { - return "owners/createOrUpdateOwnerForm"; - } - else { - this.clinicService.saveOwner(owner); - status.setComplete(); - return "redirect:/owners/" + owner.getId(); - } - } - - @RequestMapping(value = "/owners/find", method = RequestMethod.GET) - public String initFindForm(Model model) { - model.addAttribute("owner", new Owner()); - return "owners/findOwners"; - } - - @RequestMapping(value = "/owners", method = RequestMethod.GET) - public String processFindForm(Owner owner, BindingResult result, Model model) { - - // allow parameterless GET request for /owners to return all records - if (owner.getLastName() == null) { - owner.setLastName(""); // empty string signifies broadest possible search - } - - // find owners by last name - Collection<Owner> results = this.clinicService.findOwnerByLastName(owner.getLastName()); - if (results.size() < 1) { - // no owners found - result.rejectValue("lastName", "notFound", "not found"); - return "owners/findOwners"; - } - if (results.size() > 1) { - // multiple owners found - model.addAttribute("selections", results); - return "owners/ownersList"; - } - else { - // 1 owner found - owner = results.iterator().next(); - return "redirect:/owners/" + owner.getId(); - } - } - - @RequestMapping(value="/owners/{ownerId}/edit", method = RequestMethod.GET) - public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) { - Owner owner = this.clinicService.findOwnerById(ownerId); - model.addAttribute(owner); - return "owners/createOrUpdateOwnerForm"; - } - - @RequestMapping(value="/owners/{ownerId}/edit", method = RequestMethod.PUT) - public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, SessionStatus status) { - if (result.hasErrors()) { - return "owners/createOrUpdateOwnerForm"; - } - else { - this.clinicService.saveOwner(owner); - status.setComplete(); - return "redirect:/owners/{ownerId}"; - } - } - - /** - * Custom handler for displaying an owner. - * - * @param ownerId the ID of the owner to display - * @return a ModelMap with the model attributes for the view - */ - @RequestMapping("/owners/{ownerId}") - public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { - ModelAndView mav = new ModelAndView("owners/ownerDetails"); - mav.addObject(this.clinicService.findOwnerById(ownerId)); - return mav; - } + private final ClinicService clinicService; + + + @Autowired + public OwnerController(ClinicService clinicService) { + this.clinicService = clinicService; + } + + @InitBinder + public void setAllowedFields(WebDataBinder dataBinder) { + dataBinder.setDisallowedFields("id"); + } + + @RequestMapping(value = "/owners/new", method = RequestMethod.GET) + public String initCreationForm(Model model) { + Owner owner = new Owner(); + model.addAttribute(owner); + return "owners/createOrUpdateOwnerForm"; + } + + @RequestMapping(value = "/owners/new", method = RequestMethod.POST) + public String processCreationForm(@Valid Owner owner, BindingResult result, SessionStatus status) { + if (result.hasErrors()) { + return "owners/createOrUpdateOwnerForm"; + } else { + this.clinicService.saveOwner(owner); + status.setComplete(); + return "redirect:/owners/" + owner.getId(); + } + } + + @RequestMapping(value = "/owners/find", method = RequestMethod.GET) + public String initFindForm(Model model) { + model.addAttribute("owner", new Owner()); + return "owners/findOwners"; + } + + @RequestMapping(value = "/owners", method = RequestMethod.GET) + public String processFindForm(Owner owner, BindingResult result, Model model) { + + // allow parameterless GET request for /owners to return all records + if (owner.getLastName() == null) { + owner.setLastName(""); // empty string signifies broadest possible search + } + + // find owners by last name + Collection<Owner> results = this.clinicService.findOwnerByLastName(owner.getLastName()); + if (results.size() < 1) { + // no owners found + result.rejectValue("lastName", "notFound", "not found"); + return "owners/findOwners"; + } + if (results.size() > 1) { + // multiple owners found + model.addAttribute("selections", results); + return "owners/ownersList"; + } else { + // 1 owner found + owner = results.iterator().next(); + return "redirect:/owners/" + owner.getId(); + } + } + + @RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.GET) + public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) { + Owner owner = this.clinicService.findOwnerById(ownerId); + model.addAttribute(owner); + return "owners/createOrUpdateOwnerForm"; + } + + @RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.PUT) + public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, SessionStatus status) { + if (result.hasErrors()) { + return "owners/createOrUpdateOwnerForm"; + } else { + this.clinicService.saveOwner(owner); + status.setComplete(); + return "redirect:/owners/{ownerId}"; + } + } + + /** + * Custom handler for displaying an owner. + * + * @param ownerId the ID of the owner to display + * @return a ModelMap with the model attributes for the view + */ + @RequestMapping("/owners/{ownerId}") + public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { + ModelAndView mav = new ModelAndView("owners/ownerDetails"); + mav.addObject(this.clinicService.findOwnerById(ownerId)); + return mav; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/web/PetController.java b/src/main/java/org/springframework/samples/petclinic/web/PetController.java index 2c0c0b73c5f0b3fd38da05ded96f6ad32367f711..3161071d99d73bb20c4e75543d0f3475882ba2f4 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/PetController.java +++ b/src/main/java/org/springframework/samples/petclinic/web/PetController.java @@ -15,8 +15,6 @@ */ package org.springframework.samples.petclinic.web; -import java.util.Collection; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Owner; import org.springframework.samples.petclinic.model.Pet; @@ -26,16 +24,12 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; +import java.util.Collection; + /** - * * @author Juergen Hoeller * @author Ken Krebs * @author Arjen Poutsma @@ -44,65 +38,63 @@ import org.springframework.web.bind.support.SessionStatus; @SessionAttributes("pet") public class PetController { - private final ClinicService clinicService; + private final ClinicService clinicService; - @Autowired - public PetController(ClinicService clinicService) { - this.clinicService = clinicService; - } + @Autowired + public PetController(ClinicService clinicService) { + this.clinicService = clinicService; + } - @ModelAttribute("types") - public Collection<PetType> populatePetTypes() { - return this.clinicService.findPetTypes(); - } + @ModelAttribute("types") + public Collection<PetType> populatePetTypes() { + return this.clinicService.findPetTypes(); + } - @InitBinder - public void setAllowedFields(WebDataBinder dataBinder) { - dataBinder.setDisallowedFields("id"); - } + @InitBinder + public void setAllowedFields(WebDataBinder dataBinder) { + dataBinder.setDisallowedFields("id"); + } - @RequestMapping(value="/owners/{ownerId}/pets/new", method = RequestMethod.GET) - public String initCreationForm(@PathVariable("ownerId") int ownerId, Model model) { - Owner owner = this.clinicService.findOwnerById(ownerId); - Pet pet = new Pet(); - owner.addPet(pet); - model.addAttribute("pet", pet); - return "pets/createOrUpdatePetForm"; - } + @RequestMapping(value = "/owners/{ownerId}/pets/new", method = RequestMethod.GET) + public String initCreationForm(@PathVariable("ownerId") int ownerId, Model model) { + Owner owner = this.clinicService.findOwnerById(ownerId); + Pet pet = new Pet(); + owner.addPet(pet); + model.addAttribute("pet", pet); + return "pets/createOrUpdatePetForm"; + } - @RequestMapping(value="/owners/{ownerId}/pets/new", method = RequestMethod.POST) - public String processCreationForm(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) { - new PetValidator().validate(pet, result); - if (result.hasErrors()) { - return "pets/createOrUpdatePetForm"; - } - else { - this.clinicService.savePet(pet); - status.setComplete(); - return "redirect:/owners/{ownerId}"; - } - } + @RequestMapping(value = "/owners/{ownerId}/pets/new", method = RequestMethod.POST) + public String processCreationForm(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) { + new PetValidator().validate(pet, result); + if (result.hasErrors()) { + return "pets/createOrUpdatePetForm"; + } else { + this.clinicService.savePet(pet); + status.setComplete(); + return "redirect:/owners/{ownerId}"; + } + } - @RequestMapping(value="/owners/*/pets/{petId}/edit", method = RequestMethod.GET) - public String initUpdateForm(@PathVariable("petId") int petId, Model model) { - Pet pet = this.clinicService.findPetById(petId); - model.addAttribute("pet", pet); - return "pets/createOrUpdatePetForm"; - } + @RequestMapping(value = "/owners/*/pets/{petId}/edit", method = RequestMethod.GET) + public String initUpdateForm(@PathVariable("petId") int petId, Model model) { + Pet pet = this.clinicService.findPetById(petId); + model.addAttribute("pet", pet); + return "pets/createOrUpdatePetForm"; + } - @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = { RequestMethod.PUT, RequestMethod.POST }) - public String processUpdateForm(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) { - // we're not using @Valid annotation here because it is easier to define such validation rule in Java - new PetValidator().validate(pet, result); - if (result.hasErrors()) { - return "pets/createOrUpdatePetForm"; - } - else { - this.clinicService.savePet(pet); - status.setComplete(); - return "redirect:/owners/{ownerId}"; - } - } + @RequestMapping(value = "/owners/{ownerId}/pets/{petId}/edit", method = {RequestMethod.PUT, RequestMethod.POST}) + public String processUpdateForm(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) { + // we're not using @Valid annotation here because it is easier to define such validation rule in Java + new PetValidator().validate(pet, result); + if (result.hasErrors()) { + return "pets/createOrUpdatePetForm"; + } else { + this.clinicService.savePet(pet); + status.setComplete(); + return "redirect:/owners/{ownerId}"; + } + } } diff --git a/src/main/java/org/springframework/samples/petclinic/web/PetTypeFormatter.java b/src/main/java/org/springframework/samples/petclinic/web/PetTypeFormatter.java index 6217ba82f2dafc36179d1e65bcbc3fdaba041224..725f32f30f1b407c7f267437bae1a559fe143881 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/PetTypeFormatter.java +++ b/src/main/java/org/springframework/samples/petclinic/web/PetTypeFormatter.java @@ -16,52 +16,51 @@ package org.springframework.samples.petclinic.web; -import java.text.ParseException; -import java.util.Collection; -import java.util.Locale; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.Formatter; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.service.ClinicService; +import java.text.ParseException; +import java.util.Collection; +import java.util.Locale; + /** - * Instructs Spring MVC on how to parse and print elements of type 'PetType'. - * Starting from Spring 3.0, Formatters have come as an improvement in comparison to legacy PropertyEditors. - * See the following links for more details: - * - The Spring ref doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#format-Formatter-SPI + * Instructs Spring MVC on how to parse and print elements of type 'PetType'. Starting from Spring 3.0, Formatters have + * come as an improvement in comparison to legacy PropertyEditors. See the following links for more details: - The + * Spring ref doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#format-Formatter-SPI * - A nice blog entry from Gordon Dickens: http://gordondickens.com/wordpress/2010/09/30/using-spring-3-0-custom-type-converter/ - * + * <p/> * Also see how the bean 'conversionService' has been declared inside /WEB-INF/mvc-core-config.xml - * + * * @author Mark Fisher * @author Juergen Hoeller * @author Michael Isvy */ public class PetTypeFormatter implements Formatter<PetType> { - private final ClinicService clinicService; + private final ClinicService clinicService; - @Autowired - public PetTypeFormatter(ClinicService clinicService) { - this.clinicService = clinicService; - } + @Autowired + public PetTypeFormatter(ClinicService clinicService) { + this.clinicService = clinicService; + } - @Override - public String print(PetType petType, Locale locale) { - return petType.getName(); - } + @Override + public String print(PetType petType, Locale locale) { + return petType.getName(); + } - @Override - public PetType parse(String text, Locale locale) throws ParseException { - Collection<PetType> findPetTypes = this.clinicService.findPetTypes(); - for (PetType type : findPetTypes) { - if (type.getName().equals(text)) { - return type; - } - } - throw new ParseException("type not found: "+text, 0); - } + @Override + public PetType parse(String text, Locale locale) throws ParseException { + Collection<PetType> findPetTypes = this.clinicService.findPetTypes(); + for (PetType type : findPetTypes) { + if (type.getName().equals(text)) { + return type; + } + } + throw new ParseException("type not found: " + text, 0); + } } diff --git a/src/main/java/org/springframework/samples/petclinic/web/PetValidator.java b/src/main/java/org/springframework/samples/petclinic/web/PetValidator.java index fbf080e87daced6c25eaabea00ac0755e8953721..7068dd878b0ae04d6fe27a6183fb64569f718d45 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/PetValidator.java +++ b/src/main/java/org/springframework/samples/petclinic/web/PetValidator.java @@ -27,14 +27,13 @@ import org.springframework.validation.Errors; */ public class PetValidator { - public void validate(Pet pet, Errors errors) { - String name = pet.getName(); - if (!StringUtils.hasLength(name)) { - errors.rejectValue("name", "required", "required"); - } - else if (pet.isNew() && pet.getOwner().getPet(name, true) != null) { - errors.rejectValue("name", "duplicate", "already exists"); - } - } + public void validate(Pet pet, Errors errors) { + String name = pet.getName(); + if (!StringUtils.hasLength(name)) { + errors.rejectValue("name", "required", "required"); + } else if (pet.isNew() && pet.getOwner().getPet(name, true) != null) { + errors.rejectValue("name", "duplicate", "already exists"); + } + } } diff --git a/src/main/java/org/springframework/samples/petclinic/web/VetController.java b/src/main/java/org/springframework/samples/petclinic/web/VetController.java index dfbc216a7e95cb0ff5200b88253313309db093f0..0f5478556b4a9d9844a44d82bfb65a0c40f88477 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/VetController.java +++ b/src/main/java/org/springframework/samples/petclinic/web/VetController.java @@ -23,7 +23,6 @@ import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** - * * @author Juergen Hoeller * @author Mark Fisher * @author Ken Krebs @@ -32,26 +31,23 @@ import org.springframework.web.bind.annotation.RequestMapping; @Controller public class VetController { - private final ClinicService clinicService; - - - @Autowired - public VetController(ClinicService clinicService) { - this.clinicService = clinicService; - } - - @RequestMapping("/vets") - public String showVetList(Model model) { - // Here we are returning an object of type 'Vets' rather than a collection of Vet objects - // so it is simpler for Object-Xml mapping - Vets vets = new Vets(); - vets.getVetList().addAll(this.clinicService.findVets()); - model.addAttribute("vets", vets); - return "vets/vetList"; - } + private final ClinicService clinicService; + @Autowired + public VetController(ClinicService clinicService) { + this.clinicService = clinicService; + } + @RequestMapping("/vets") + public String showVetList(Model model) { + // Here we are returning an object of type 'Vets' rather than a collection of Vet objects + // so it is simpler for Object-Xml mapping + Vets vets = new Vets(); + vets.getVetList().addAll(this.clinicService.findVets()); + model.addAttribute("vets", vets); + return "vets/vetList"; + } } diff --git a/src/main/java/org/springframework/samples/petclinic/web/VetsAtomView.java b/src/main/java/org/springframework/samples/petclinic/web/VetsAtomView.java index 6df94372ef8a700e81ab26e7541dbd69f9f1e930..d379aebf1412185c27af4b7a918fb6e14bafcc28 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/VetsAtomView.java +++ b/src/main/java/org/springframework/samples/petclinic/web/VetsAtomView.java @@ -15,60 +15,58 @@ */ package org.springframework.samples.petclinic.web; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - +import com.sun.syndication.feed.atom.Content; +import com.sun.syndication.feed.atom.Entry; +import com.sun.syndication.feed.atom.Feed; import org.springframework.samples.petclinic.model.Vet; import org.springframework.samples.petclinic.model.Vets; import org.springframework.web.servlet.view.feed.AbstractAtomFeedView; -import com.sun.syndication.feed.atom.Content; -import com.sun.syndication.feed.atom.Entry; -import com.sun.syndication.feed.atom.Feed; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; /** - * A view creating a Atom representation from a list of Visit objects. - * + * A view creating a Atom representation from a list of Visit objects. + * * @author Alef Arendsen * @author Arjen Poutsma */ public class VetsAtomView extends AbstractAtomFeedView { - @Override - protected void buildFeedMetadata(Map<String, Object> model, Feed feed, HttpServletRequest request) { - feed.setId("tag:springsource.org"); - feed.setTitle("Veterinarians"); - //feed.setUpdated(date); - } + @Override + protected void buildFeedMetadata(Map<String, Object> model, Feed feed, HttpServletRequest request) { + feed.setId("tag:springsource.org"); + feed.setTitle("Veterinarians"); + //feed.setUpdated(date); + } + + @Override + protected List<Entry> buildFeedEntries(Map<String, Object> model, + HttpServletRequest request, HttpServletResponse response) throws Exception { - @Override - protected List<Entry> buildFeedEntries(Map<String, Object> model, - HttpServletRequest request, HttpServletResponse response) throws Exception { + Vets vets = (Vets) model.get("vets"); + List<Vet> vetList = vets.getVetList(); + List<Entry> entries = new ArrayList<Entry>(vetList.size()); - Vets vets = (Vets) model.get("vets"); - List<Vet> vetList = vets.getVetList(); - List<Entry> entries = new ArrayList<Entry>(vetList.size()); + for (Vet vet : vetList) { + Entry entry = new Entry(); + // see http://diveintomark.org/archives/2004/05/28/howto-atom-id#other + entry.setId(String.format("tag:springsource.org,%s", vet.getId())); + entry.setTitle(String.format("Vet: %s %s", vet.getFirstName(), vet.getLastName())); + //entry.setUpdated(visit.getDate().toDate()); - for (Vet vet : vetList) { - Entry entry = new Entry(); - // see http://diveintomark.org/archives/2004/05/28/howto-atom-id#other - entry.setId(String.format("tag:springsource.org,%s", vet.getId())); - entry.setTitle(String.format("Vet: %s %s", vet.getFirstName(), vet.getLastName())); - //entry.setUpdated(visit.getDate().toDate()); + Content summary = new Content(); + summary.setValue(vet.getSpecialties().toString()); + entry.setSummary(summary); - Content summary = new Content(); - summary.setValue(vet.getSpecialties().toString()); - entry.setSummary(summary); + entries.add(entry); + } + response.setContentType("blabla"); + return entries; - entries.add(entry); - } - response.setContentType("blabla"); - return entries; + } - } - } diff --git a/src/main/java/org/springframework/samples/petclinic/web/VisitController.java b/src/main/java/org/springframework/samples/petclinic/web/VisitController.java index b72e0cad356a1ecfe2180a37a67cfe61a1dd6858..7de96693931f9890c80ca77454826d2f60fed2fe 100644 --- a/src/main/java/org/springframework/samples/petclinic/web/VisitController.java +++ b/src/main/java/org/springframework/samples/petclinic/web/VisitController.java @@ -15,8 +15,6 @@ */ package org.springframework.samples.petclinic.web; -import javax.validation.Valid; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.Visit; @@ -25,16 +23,13 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; +import javax.validation.Valid; + /** - * * @author Juergen Hoeller * @author Ken Krebs * @author Arjen Poutsma @@ -44,45 +39,44 @@ import org.springframework.web.servlet.ModelAndView; @SessionAttributes("visit") public class VisitController { - private final ClinicService clinicService; + private final ClinicService clinicService; - @Autowired - public VisitController(ClinicService clinicService) { - this.clinicService = clinicService; - } + @Autowired + public VisitController(ClinicService clinicService) { + this.clinicService = clinicService; + } - @InitBinder - public void setAllowedFields(WebDataBinder dataBinder) { - dataBinder.setDisallowedFields("id"); - } + @InitBinder + public void setAllowedFields(WebDataBinder dataBinder) { + dataBinder.setDisallowedFields("id"); + } - @RequestMapping(value="/owners/*/pets/{petId}/visits/new", method = RequestMethod.GET) - public String initNewVisitForm(@PathVariable("petId") int petId, Model model) { - Pet pet = this.clinicService.findPetById(petId); - Visit visit = new Visit(); - pet.addVisit(visit); - model.addAttribute("visit", visit); - return "pets/createOrUpdateVisitForm"; - } + @RequestMapping(value = "/owners/*/pets/{petId}/visits/new", method = RequestMethod.GET) + public String initNewVisitForm(@PathVariable("petId") int petId, Model model) { + Pet pet = this.clinicService.findPetById(petId); + Visit visit = new Visit(); + pet.addVisit(visit); + model.addAttribute("visit", visit); + return "pets/createOrUpdateVisitForm"; + } - @RequestMapping(value="/owners/{ownerId}/pets/{petId}/visits/new", method = RequestMethod.POST) - public String processNewVisitForm(@Valid Visit visit, BindingResult result, SessionStatus status) { - if (result.hasErrors()) { - return "pets/createOrUpdateVisitForm"; - } - else { - this.clinicService.saveVisit(visit); - status.setComplete(); - return "redirect:/owners/{ownerId}"; - } - } + @RequestMapping(value = "/owners/{ownerId}/pets/{petId}/visits/new", method = RequestMethod.POST) + public String processNewVisitForm(@Valid Visit visit, BindingResult result, SessionStatus status) { + if (result.hasErrors()) { + return "pets/createOrUpdateVisitForm"; + } else { + this.clinicService.saveVisit(visit); + status.setComplete(); + return "redirect:/owners/{ownerId}"; + } + } - @RequestMapping(value="/owners/*/pets/{petId}/visits", method=RequestMethod.GET) - public ModelAndView showVisits(@PathVariable int petId) { - ModelAndView mav = new ModelAndView("visitList"); - mav.addObject("visits", this.clinicService.findPetById(petId).getVisits()); - return mav; - } + @RequestMapping(value = "/owners/*/pets/{petId}/visits", method = RequestMethod.GET) + public ModelAndView showVisits(@PathVariable int petId) { + ModelAndView mav = new ModelAndView("visitList"); + mav.addObject("visits", this.clinicService.findPetById(petId).getVisits()); + return mav; + } } diff --git a/src/main/java/overview.html b/src/main/java/overview.html index 1eb7a2e8c194f8fac74dd8a8eabc4ccbe753d8d8..df4f4d6b7fb8f9f0a0dc3befe95d923f3019516e 100644 --- a/src/main/java/overview.html +++ b/src/main/java/overview.html @@ -1,7 +1,7 @@ <html> <body> <p> -The Spring Data Binding framework, an internal library used by Spring Web Flow. + The Spring Data Binding framework, an internal library used by Spring Web Flow. </p> </body> </html> \ No newline at end of file diff --git a/src/main/resources/db/hsqldb/initDB.sql b/src/main/resources/db/hsqldb/initDB.sql index a76d662dd809fc9f9292f8013e51b76941b7916d..a16c42decececbc48a6ef27748bbbe5288c2e247 100644 --- a/src/main/resources/db/hsqldb/initDB.sql +++ b/src/main/resources/db/hsqldb/initDB.sql @@ -1,64 +1,64 @@ -drop table vet_specialties if exists; -drop table vets if exists; -drop table specialties if exists; -drop table visits if exists; -drop table pets if exists; -drop table types if exists; -drop table owners if exists; +DROP TABLE vet_specialties IF EXISTS; +DROP TABLE vets IF EXISTS; +DROP TABLE specialties IF EXISTS; +DROP TABLE visits IF EXISTS; +DROP TABLE pets IF EXISTS; +DROP TABLE types IF EXISTS; +DROP TABLE owners IF EXISTS; CREATE TABLE vets ( - id INTEGER IDENTITY PRIMARY KEY, - first_name VARCHAR(30), - last_name VARCHAR(30) + id INTEGER IDENTITY PRIMARY KEY, + first_name VARCHAR(30), + last_name VARCHAR(30) ); -CREATE INDEX vets_last_name ON vets(last_name); +CREATE INDEX vets_last_name ON vets (last_name); CREATE TABLE specialties ( - id INTEGER IDENTITY PRIMARY KEY, - name VARCHAR(80) + id INTEGER IDENTITY PRIMARY KEY, + name VARCHAR(80) ); -CREATE INDEX specialties_name ON specialties(name); +CREATE INDEX specialties_name ON specialties (name); CREATE TABLE vet_specialties ( - vet_id INTEGER NOT NULL, - specialty_id INTEGER NOT NULL + vet_id INTEGER NOT NULL, + specialty_id INTEGER NOT NULL ); -alter table vet_specialties add constraint fk_vet_specialties_vets foreign key (vet_id) references vets(id); -alter table vet_specialties add constraint fk_vet_specialties_specialties foreign key (specialty_id) references specialties(id); +ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_vets FOREIGN KEY (vet_id) REFERENCES vets (id); +ALTER TABLE vet_specialties ADD CONSTRAINT fk_vet_specialties_specialties FOREIGN KEY (specialty_id) REFERENCES specialties (id); CREATE TABLE types ( - id INTEGER IDENTITY PRIMARY KEY, - name VARCHAR(80) + id INTEGER IDENTITY PRIMARY KEY, + name VARCHAR(80) ); -CREATE INDEX types_name ON types(name); +CREATE INDEX types_name ON types (name); CREATE TABLE owners ( - id INTEGER IDENTITY PRIMARY KEY, - first_name VARCHAR(30), - last_name VARCHAR(30), - address VARCHAR(255), - city VARCHAR(80), - telephone VARCHAR(20) + id INTEGER IDENTITY PRIMARY KEY, + first_name VARCHAR(30), + last_name VARCHAR(30), + address VARCHAR(255), + city VARCHAR(80), + telephone VARCHAR(20) ); -CREATE INDEX owners_last_name ON owners(last_name); +CREATE INDEX owners_last_name ON owners (last_name); CREATE TABLE pets ( - id INTEGER IDENTITY PRIMARY KEY, - name VARCHAR(30), - birth_date DATE, - type_id INTEGER NOT NULL, - owner_id INTEGER NOT NULL + id INTEGER IDENTITY PRIMARY KEY, + name VARCHAR(30), + birth_date DATE, + type_id INTEGER NOT NULL, + owner_id INTEGER NOT NULL ); -alter table pets add constraint fk_pets_owners foreign key (owner_id) references owners(id); -alter table pets add constraint fk_pets_types foreign key (type_id) references types(id); -CREATE INDEX pets_name ON pets(name); +ALTER TABLE pets ADD CONSTRAINT fk_pets_owners FOREIGN KEY (owner_id) REFERENCES owners (id); +ALTER TABLE pets ADD CONSTRAINT fk_pets_types FOREIGN KEY (type_id) REFERENCES types (id); +CREATE INDEX pets_name ON pets (name); CREATE TABLE visits ( - id INTEGER IDENTITY PRIMARY KEY, - pet_id INTEGER NOT NULL, - visit_date DATE, - description VARCHAR(255) + id INTEGER IDENTITY PRIMARY KEY, + pet_id INTEGER NOT NULL, + visit_date DATE, + description VARCHAR(255) ); -alter table visits add constraint fk_visits_pets foreign key (pet_id) references pets(id); -CREATE INDEX visits_pet_id ON visits(pet_id); +ALTER TABLE visits ADD CONSTRAINT fk_visits_pets FOREIGN KEY (pet_id) REFERENCES pets (id); +CREATE INDEX visits_pet_id ON visits (pet_id); diff --git a/src/main/resources/ehcache.xml b/src/main/resources/ehcache.xml index 8167066b136a779deebee14bccbe691337f0d40d..32e509953fb574c4d8d553f990121c766ac8a470 100644 --- a/src/main/resources/ehcache.xml +++ b/src/main/resources/ehcache.xml @@ -1,17 +1,17 @@ <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="ehcache.xsd" - updateCheck="false"> + xsi:noNamespaceSchemaLocation="ehcache.xsd" + updateCheck="false"> <diskStore path="java.io.tmpdir"/> - <!-- objects are evicted from the cache every 60 seconds --> + <!-- objects are evicted from the cache every 60 seconds --> <cache name="vets" - timeToLiveSeconds="60" - maxElementsInMemory="100" - eternal="false" - overflowToDisk="false" - maxElementsOnDisk="10000000" - diskPersistent="false" - diskExpiryThreadIntervalSeconds="1" - memoryStoreEvictionPolicy="LRU" /> - + timeToLiveSeconds="60" + maxElementsInMemory="100" + eternal="false" + overflowToDisk="false" + maxElementsOnDisk="10000000" + diskPersistent="false" + diskExpiryThreadIntervalSeconds="1" + memoryStoreEvictionPolicy="LRU"/> + </ehcache> diff --git a/src/main/resources/ehcache.xsd b/src/main/resources/ehcache.xsd index 2a539199fed4c3b0951b686afd5fa5ac6f989450..bfc19ddb1e7d3c2f437ad36c129b5520f6c46f87 100644 --- a/src/main/resources/ehcache.xsd +++ b/src/main/resources/ehcache.xsd @@ -227,13 +227,13 @@ </xs:element> <xs:element name="searchable"> - <xs:complexType> - <xs:sequence> - <xs:element minOccurs="0" maxOccurs="unbounded" ref="searchAttribute"/> - </xs:sequence> - <xs:attribute name="keys" use="optional" type="xs:boolean" default="true"/> - <xs:attribute name="values" use="optional" type="xs:boolean" default="true"/> - </xs:complexType> + <xs:complexType> + <xs:sequence> + <xs:element minOccurs="0" maxOccurs="unbounded" ref="searchAttribute"/> + </xs:sequence> + <xs:attribute name="keys" use="optional" type="xs:boolean" default="true"/> + <xs:attribute name="values" use="optional" type="xs:boolean" default="true"/> + </xs:complexType> </xs:element> <xs:element name="pinning"> @@ -371,26 +371,27 @@ <xs:element name="sizeOfPolicy"> <xs:complexType> <xs:attribute name="maxDepth" use="required" type="xs:integer"/> - <xs:attribute name="maxDepthExceededBehavior" use="optional" default="continue" type="maxDepthExceededBehavior"/> + <xs:attribute name="maxDepthExceededBehavior" use="optional" default="continue" + type="maxDepthExceededBehavior"/> </xs:complexType> </xs:element> - <xs:element name="persistence"> - <xs:complexType> + <xs:element name="persistence"> + <xs:complexType> <xs:attribute name="strategy" use="required" type="persistenceStrategy"/> <xs:attribute name="synchronousWrites" use="optional" default="false" type="xs:boolean"/> - </xs:complexType> - </xs:element> - - <xs:simpleType name="persistenceStrategy"> - <xs:restriction base="xs:string"> - <xs:enumeration value="localTempSwap"/> - <xs:enumeration value="localRestartable"/> - <xs:enumeration value="none"/> - <xs:enumeration value="distributed"/> - </xs:restriction> - </xs:simpleType> - + </xs:complexType> + </xs:element> + + <xs:simpleType name="persistenceStrategy"> + <xs:restriction base="xs:string"> + <xs:enumeration value="localTempSwap"/> + <xs:enumeration value="localRestartable"/> + <xs:enumeration value="none"/> + <xs:enumeration value="distributed"/> + </xs:restriction> + </xs:simpleType> + <xs:simpleType name="maxDepthExceededBehavior"> <xs:restriction base="xs:string"> <xs:enumeration value="continue"/> diff --git a/src/main/resources/spring/dao-config.xml b/src/main/resources/spring/dao-config.xml index e5b8346aac5bf99ef6010222fd456261ac6b6271..c29a9bd4ca5e36182e10b7cd4ad8f99e4ff229f9 100644 --- a/src/main/resources/spring/dao-config.xml +++ b/src/main/resources/spring/dao-config.xml @@ -1,14 +1,21 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- - Application context definition for PetClinic on JPA. + Application context definition for PetClinic on JPA. --> -<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:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" - xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd - http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd - http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> +<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:tx="http://www.springframework.org/schema/tx" + xmlns:jpa="http://www.springframework.org/schema/data/jpa" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/data/jpa + http://www.springframework.org/schema/data/jpa/spring-jpa.xsd + http://www.springframework.org/schema/tx + http://www.springframework.org/schema/tx/spring-tx.xsd + http://www.springframework.org/schema/context + http://www.springframework.org/schema/context/spring-context.xsd"> <!-- ========================= RESOURCE DEFINITIONS ========================= --> @@ -33,7 +40,7 @@ <!-- Instruct Spring to perform declarative transaction management automatically on annotated classes. - + for mode="aspectj"/ see SPR-6392 --> <tx:annotation-driven/> @@ -46,8 +53,9 @@ <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:database="${jpa.database}" p:showSql="${jpa.showSql}"/> </property> + <!-- gDickens: BOTH Persistence Unit and Packages to Scan are NOT compatible, persistenceUnit will win --> <property name="persistenceUnitName" value="petclinic"/> - <property name="packagesToScan" value="org/springframework/samples/petclinic"/> + <property name="packagesToScan" value="org.springframework.samples.petclinic"/> </bean> <!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) --> @@ -78,7 +86,6 @@ </bean> <context:component-scan base-package="org.springframework.samples.petclinic.repository.jdbc"/> - </beans> <beans profile="jpa"> @@ -88,7 +95,6 @@ PersistenceExceptions will be auto-translated due to @Repository. --> <context:component-scan base-package="org.springframework.samples.petclinic.repository.jpa"/> - </beans> <beans profile="spring-data-jpa"> @@ -97,6 +103,5 @@ <!-- Custom configuration for the custom implementation based on JPA --> <bean id="owerRepository" class="org.springframework.samples.petclinic.repository.springdatajpa.JpaOwnerRepositoryImpl"/> - </beans> </beans> \ No newline at end of file diff --git a/src/main/resources/spring/datasource-config.xml b/src/main/resources/spring/datasource-config.xml index d803c0a2f536be1667bf0643d63f1c3f6000cd3f..2efe12010fe16400078c36a7a9fb60f2da0f133d 100644 --- a/src/main/resources/spring/datasource-config.xml +++ b/src/main/resources/spring/datasource-config.xml @@ -1,37 +1,39 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- - Application context definition for PetClinic Datasource. + Application context definition for PetClinic Datasource. --> <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:jdbc="http://www.springframework.org/schema/jdbc" - 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> - - <!-- ========================= DATASOURCE DEFINITION ========================= --> + xmlns:p="http://www.springframework.org/schema/p" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:jdbc="http://www.springframework.org/schema/jdbc" + 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/jdbc + http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> - <!-- Configurer that replaces ${...} placeholders with values from a properties file --> - <!-- (in this case, JDBC-related settings for the dataSource definition below) --> - <context:property-placeholder location="classpath:spring/jdbc.properties"/> + <!-- ========================= DATASOURCE DEFINITION ========================= --> - <!-- DataSource configuration for Apache Commons DBCP. --> - <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" - p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" - p:username="${jdbc.username}" p:password="${jdbc.password}"/> - - <!-- JNDI DataSource for JEE environments --> - <!-- - <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/petclinic"/> - --> + <!-- Configurer that replaces ${...} placeholders with values from a properties file --> + <!-- (in this case, JDBC-related settings for the dataSource definition below) --> + <context:property-placeholder location="classpath:spring/jdbc.properties"/> - <!-- Database initializer. If any of the script fails, the initialization stops. --> - <!-- As an alternative, for embedded databases see <jdbc:embedded-database/>. --> - <jdbc:initialize-database data-source="dataSource"> - <jdbc:script location="${jdbc.initLocation}"/> - <jdbc:script location="${jdbc.dataLocation}"/> - </jdbc:initialize-database> + <!-- DataSource configuration for Apache Commons DBCP. --> + <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" + p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" + p:username="${jdbc.username}" p:password="${jdbc.password}"/> + + <!-- JNDI DataSource for JEE environments --> + <!-- + <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/petclinic"/> + --> + + <!-- Database initializer. If any of the script fails, the initialization stops. --> + <!-- As an alternative, for embedded databases see <jdbc:embedded-database/>. --> + <jdbc:initialize-database data-source="dataSource"> + <jdbc:script location="${jdbc.initLocation}"/> + <jdbc:script location="${jdbc.dataLocation}"/> + </jdbc:initialize-database> </beans> \ No newline at end of file diff --git a/src/main/resources/spring/jdbc.properties b/src/main/resources/spring/jdbc.properties index 214778bdc63bd264be3c8ebd0f86c800d9bc9b3a..21d1560b4cc615df5693f1e37d2ad4a10759ae8d 100644 --- a/src/main/resources/spring/jdbc.properties +++ b/src/main/resources/spring/jdbc.properties @@ -4,9 +4,6 @@ # various application context XML files (e.g., "applicationContext-*.xml"). # Targeted at system administrators, to avoid touching the context XML files. - - - #------------------------------------------------------------------------------- # HSQL Settings diff --git a/src/main/resources/spring/mvc-core-config.xml b/src/main/resources/spring/mvc-core-config.xml index d814c256df8ed99d027dbe0cf5c40d410f936363..8aa5d61f0ba0c0d7747df79967def893cc2cabb3 100644 --- a/src/main/resources/spring/mvc-core-config.xml +++ b/src/main/resources/spring/mvc-core-config.xml @@ -1,57 +1,63 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- - - DispatcherServlet application context for PetClinic's web tier. + - 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" xmlns:mvc="http://www.springframework.org/schema/mvc" - xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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"> - - <import resource="mvc-view-config.xml"/> - - <!-- - - POJOs labeled with the @Controller and @Service annotations are auto-detected. - --> - <context:component-scan base-package="org.springframework.samples.petclinic.web, org.springframework.samples.petclinic.service"/> - - <mvc:annotation-driven conversion-service="conversionService" /> - - <!-- all resources inside folder src/main/webapp/resources are mapped so they can be refered to inside JSP files - (see header.jsp for more details) --> - <mvc:resources mapping="/resources/**" location="/resources/"/> - - <!-- uses WebJars so Javascript and CSS libs can be declared as Maven dependencies (Bootstrap, jQuery...) --> - <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/> - - <mvc:view-controller path="/" view-name="welcome"/> - - - <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> - <property name="formatters"> - <set> - <bean class="org.springframework.samples.petclinic.web.PetTypeFormatter" /> - </set> - </property> - </bean> - - <!-- - - Message source for this context, loaded from localized "messages_xx" files. - - Files are stored inside src/main/resources - --> - <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" - p:basename="messages/messages"/> - - <!-- - - This bean resolves specific types of exceptions to corresponding logical - - view names for error views. - --> - <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> - <!-- view name resolved using bean of type InternalResourceViewResolver (declared in mvc-view-config.xml) --> - <property name="defaultErrorView" value="exception"/> <!-- results into 'WEB-INF/jsp/exception.jsp' --> - <property name="warnLogCategory" value="warn"/> <!-- needed otherwise exceptions won't be logged anywhere --> - </bean> +<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:mvc="http://www.springframework.org/schema/mvc" + xsi:schemaLocation="http://www.springframework.org/schema/mvc + http://www.springframework.org/schema/mvc/spring-mvc.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"> + + <import resource="mvc-view-config.xml"/> + + <!-- + - POJOs labeled with the @Controller and @Service annotations are auto-detected. + --> + <context:component-scan + base-package="org.springframework.samples.petclinic.web, org.springframework.samples.petclinic.service"/> + + <mvc:annotation-driven conversion-service="conversionService"/> + + <!-- all resources inside folder src/main/webapp/resources are mapped so they can be refered to inside JSP files + (see header.jsp for more details) --> + <mvc:resources mapping="/resources/**" location="/resources/"/> + + <!-- uses WebJars so Javascript and CSS libs can be declared as Maven dependencies (Bootstrap, jQuery...) --> + <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/> + + <mvc:view-controller path="/" view-name="welcome"/> + + <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> + <property name="formatters"> + <set> + <bean class="org.springframework.samples.petclinic.web.PetTypeFormatter"/> + </set> + </property> + </bean> + + <!-- + - Message source for this context, loaded from localized "messages_xx" files. + - Files are stored inside src/main/resources + --> + <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" + p:basename="messages/messages"/> + + <!-- + - This bean resolves specific types of exceptions to corresponding logical + - view names for error views. + --> + <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> + <!-- view name resolved using bean of type InternalResourceViewResolver (declared in mvc-view-config.xml) --> + <property name="defaultErrorView" value="exception"/> + <!-- results into 'WEB-INF/jsp/exception.jsp' --> + <property name="warnLogCategory" value="warn"/> + <!-- needed otherwise exceptions won't be logged anywhere --> + </bean> </beans> diff --git a/src/main/resources/spring/mvc-view-config.xml b/src/main/resources/spring/mvc-view-config.xml index 053fa3fdb5b19b60796e086abd525e2c1194b23f..8425754acc4a273c56f407646f41d72b6e6fc634 100644 --- a/src/main/resources/spring/mvc-view-config.xml +++ b/src/main/resources/spring/mvc-view-config.xml @@ -2,52 +2,50 @@ <!-- - 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" xmlns:mvc="http://www.springframework.org/schema/mvc" - xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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 ContentNegotiatingViewResolver delegates to the InternalResourceViewResolver and BeanNameViewResolver, - - and uses the requested media type (determined by the path extension) to pick a matching view. - - When the media type is 'text/html', it will delegate to the InternalResourceViewResolver's JstlView, - - otherwise to the BeanNameViewResolver. - --> - <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> - <property name="contentNegotiationManager" ref="cnManager"/> - </bean> - - <!-- Simple strategy: only path extension is taken into account --> - <bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> - <property name="favorPathExtension" value="true"/> - <property name="ignoreAcceptHeader" value="true"/> - </bean> - - <!-- Default viewClass: JSTL view (JSP with html output) --> - <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> - <!-- Example: a logical view name of 'vets' is mapped to '/WEB-INF/jsp/vets.jsp' --> - <property name="prefix" value="/WEB-INF/jsp/" /> - <property name="suffix" value=".jsp" /> - </bean> - - <!-- Used here for 'xml' and 'atom' views --> - <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> - - <!-- Renders an Atom feed of the visits. Used by the BeanNameViewResolver --> - <bean id="vets/vetList.atom" class="org.springframework.samples.petclinic.web.VetsAtomView"/> - - <!-- Renders an XML view. Used by the BeanNameViewResolver --> - <bean id="vets/vetList.xml" class="org.springframework.web.servlet.view.xml.MarshallingView"> - <property name="marshaller" ref="marshaller"/> - </bean> - - <oxm:jaxb2-marshaller id="marshaller"> - <!-- Object-XML mapping declared using annotations inside 'Vets' --> - <oxm:class-to-be-bound name="org.springframework.samples.petclinic.model.Vets"/> - </oxm:jaxb2-marshaller> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:oxm="http://www.springframework.org/schema/oxm" + xsi:schemaLocation="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"> + <!-- + - The ContentNegotiatingViewResolver delegates to the InternalResourceViewResolver and BeanNameViewResolver, + - and uses the requested media type (determined by the path extension) to pick a matching view. + - When the media type is 'text/html', it will delegate to the InternalResourceViewResolver's JstlView, + - otherwise to the BeanNameViewResolver. + --> + <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> + <property name="contentNegotiationManager" ref="cnManager"/> + </bean> + + <!-- Simple strategy: only path extension is taken into account --> + <bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> + <property name="favorPathExtension" value="true"/> + <property name="ignoreAcceptHeader" value="true"/> + </bean> + + <!-- Default viewClass: JSTL view (JSP with html output) --> + <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> + <!-- Example: a logical view name of 'vets' is mapped to '/WEB-INF/jsp/vets.jsp' --> + <property name="prefix" value="/WEB-INF/jsp/"/> + <property name="suffix" value=".jsp"/> + </bean> + + <!-- Used here for 'xml' and 'atom' views --> + <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> + + <!-- Renders an Atom feed of the visits. Used by the BeanNameViewResolver --> + <bean id="vets/vetList.atom" class="org.springframework.samples.petclinic.web.VetsAtomView"/> + + <!-- Renders an XML view. Used by the BeanNameViewResolver --> + <bean id="vets/vetList.xml" class="org.springframework.web.servlet.view.xml.MarshallingView"> + <property name="marshaller" ref="marshaller"/> + </bean> + + <oxm:jaxb2-marshaller id="marshaller"> + <!-- Object-XML mapping declared using annotations inside 'Vets' --> + <oxm:class-to-be-bound name="org.springframework.samples.petclinic.model.Vets"/> + </oxm:jaxb2-marshaller> </beans> diff --git a/src/main/resources/spring/tools-config.xml b/src/main/resources/spring/tools-config.xml index cf204ba2a08335740578b49de5abf37ccc695102..e64c18931773a3ebe70c0341d56a9b48131e4a08 100644 --- a/src/main/resources/spring/tools-config.xml +++ b/src/main/resources/spring/tools-config.xml @@ -2,44 +2,48 @@ <!-- Application context definition for PetClinic on JPA. --> -<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" - xmlns:cache="http://www.springframework.org/schema/cache" - xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd - http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd - http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> - - <!-- - Simply defining this bean will cause requests to owner names to be saved. - This aspect is defined in petclinic.jar's META-INF/aop.xml file. - Note that we can dependency inject this bean like any other bean. - --> - <aop:aspectj-autoproxy> - <aop:include name="callMonitor"/> - </aop:aspectj-autoproxy> - - <!-- Call monitoring aspect that monitors call count and call invocation time --> - <bean id="callMonitor" class="org.springframework.samples.petclinic.util.CallMonitoringAspect"/> - - <!-- - Exporter that exposes the CallMonitoringAspect via JMX, - based on the @ManagedResource, @ManagedAttribute, and @ManagedOperation annotations. - --> - <context:mbean-export /> - - <!-- enables scanning for @Cacheable annotation --> - <cache:annotation-driven /> - - <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> - <property name="cacheManager" ref="ehcache"/> - </bean> - +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:cache="http://www.springframework.org/schema/cache" + xsi:schemaLocation="http://www.springframework.org/schema/aop + http://www.springframework.org/schema/aop/spring-aop.xsd + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/cache + http://www.springframework.org/schema/cache/spring-cache.xsd + http://www.springframework.org/schema/context + http://www.springframework.org/schema/context/spring-context.xsd"> + + <!-- + Simply defining this bean will cause requests to owner names to be saved. + This aspect is defined in petclinic.jar's META-INF/aop.xml file. + Note that we can dependency inject this bean like any other bean. + --> + <aop:aspectj-autoproxy> + <aop:include name="callMonitor"/> + </aop:aspectj-autoproxy> + + <!-- Call monitoring aspect that monitors call count and call invocation time --> + <bean id="callMonitor" class="org.springframework.samples.petclinic.util.CallMonitoringAspect"/> + + <!-- + Exporter that exposes the CallMonitoringAspect via JMX, + based on the @ManagedResource, @ManagedAttribute, and @ManagedOperation annotations. + --> + <context:mbean-export/> + + <!-- enables scanning for @Cacheable annotation --> + <cache:annotation-driven/> + + <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> + <property name="cacheManager" ref="ehcache"/> + </bean> + <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> - <property name="configLocation" value="classpath:ehcache.xml"/> + <property name="configLocation" value="classpath:ehcache.xml"/> </bean> - - - - + + </beans> \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/jsp/exception.jsp b/src/main/webapp/WEB-INF/jsp/exception.jsp index 42c7e29a25804d6d6e2ec9156696dbfc235d353a..86416dbaaaa692928679a45524eb9e04445b6dfd 100644 --- a/src/main/webapp/WEB-INF/jsp/exception.jsp +++ b/src/main/webapp/WEB-INF/jsp/exception.jsp @@ -1,27 +1,29 @@ <html lang="en"> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <jsp:include page="fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="fragments/bodyHeader.jsp"/> - <spring:url value="/resources/images/pets.png" var="petsImage"/> - <img src="${petsImage}" /> - <h2>Something happened...</h2> - <p>${exception.message}</p> - - <!-- Exception: ${exception.message}. +<div class="container"> + <jsp:include page="fragments/bodyHeader.jsp"/> + <spring:url value="/resources/images/pets.png" var="petsImage"/> + <img src="${petsImage}"/> + + <h2>Something happened...</h2> + + <p>${exception.message}</p> + + <!-- Exception: ${exception.message}. <c:forEach items="${exception.stackTrace}" var="stackTrace"> ${stackTrace} </c:forEach> --> - - - <jsp:include page="fragments/footer.jsp"/> - </div> + + <jsp:include page="fragments/footer.jsp"/> + +</div> </body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/fragments/bodyHeader.jsp b/src/main/webapp/WEB-INF/jsp/fragments/bodyHeader.jsp index f8f4645c75c20e033c79617f5d4d7d92cff9cdea..76c18441738461939ec6b004a082d9e3d48d2714 100644 --- a/src/main/webapp/WEB-INF/jsp/fragments/bodyHeader.jsp +++ b/src/main/webapp/WEB-INF/jsp/fragments/bodyHeader.jsp @@ -2,16 +2,23 @@ <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <spring:url value="/resources/images/banner-graphic.png" var="banner"/> -<img src="${banner}" /> -<div class="navbar" style="width: 601px;"> - <div class="navbar-inner"> - <ul class="nav"> - <li style="width: 100px;"><a href="<spring:url value="/" htmlEscape="true" />"><i class="icon-home"></i> Home</a></li> - <li style="width: 130px;"><a href="<spring:url value="/owners/find.html" htmlEscape="true" />"><i class="icon-search"></i> Find owners</a></li> - <li style="width: 140px;"><a href="<spring:url value="/vets.html" htmlEscape="true" />"><i class="icon-th-list"></i> Veterinarians</a></li> - <li style="width: 90px;"><a href="<spring:url value="/oups.html" htmlEscape="true" />" title="trigger a RuntimeException to see how it is handled"><i class="icon-warning-sign"></i> Error</a></li> - <li style="width: 80px;"><a href="#" title="not available yet. Work in progress!!"><i class=" icon-question-sign"></i> Help</a></li> - </ul> - </div> +<img src="${banner}"/> + +<div class="navbar" style="width: 601px;"> + <div class="navbar-inner"> + <ul class="nav"> + <li style="width: 100px;"><a href="<spring:url value="/" htmlEscape="true" />"><i class="icon-home"></i> + Home</a></li> + <li style="width: 130px;"><a href="<spring:url value="/owners/find.html" htmlEscape="true" />"><i + class="icon-search"></i> Find owners</a></li> + <li style="width: 140px;"><a href="<spring:url value="/vets.html" htmlEscape="true" />"><i + class="icon-th-list"></i> Veterinarians</a></li> + <li style="width: 90px;"><a href="<spring:url value="/oups.html" htmlEscape="true" />" + title="trigger a RuntimeException to see how it is handled"><i + class="icon-warning-sign"></i> Error</a></li> + <li style="width: 80px;"><a href="#" title="not available yet. Work in progress!!"><i + class=" icon-question-sign"></i> Help</a></li> + </ul> + </div> </div> diff --git a/src/main/webapp/WEB-INF/jsp/fragments/footer.jsp b/src/main/webapp/WEB-INF/jsp/fragments/footer.jsp index a031e66cfbb2fa11f68851bb01183da5c75e6dbf..dccec75d2dd93b16fb99c1ed37b48bf9d1630d02 100644 --- a/src/main/webapp/WEB-INF/jsp/fragments/footer.jsp +++ b/src/main/webapp/WEB-INF/jsp/fragments/footer.jsp @@ -1,10 +1,11 @@ <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> - <table class="footer"> +<table class="footer"> <tr> - <td></td> - <td align="right"><img src="<spring:url value="/resources/images/springsource-logo.png" htmlEscape="true" />" alt="Sponsored by SpringSource"/></td> + <td></td> + <td align="right"><img src="<spring:url value="/resources/images/springsource-logo.png" htmlEscape="true" />" + alt="Sponsored by SpringSource"/></td> </tr> - </table> +</table> diff --git a/src/main/webapp/WEB-INF/jsp/fragments/headTag.jsp b/src/main/webapp/WEB-INF/jsp/fragments/headTag.jsp index bfcd938380c240a30c81915e734247b9b10993c6..c1be474c24e628943b5d740c0941a9cbdc3ff16d 100644 --- a/src/main/webapp/WEB-INF/jsp/fragments/headTag.jsp +++ b/src/main/webapp/WEB-INF/jsp/fragments/headTag.jsp @@ -1,28 +1,28 @@ <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <!-- - PetClinic :: a Spring Framework demonstration +PetClinic :: a Spring Framework demonstration --> <head> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> - <title>PetClinic :: a Spring Framework demonstration</title> - - - <spring:url value="/webjars/bootstrap/2.2.1/css/bootstrap.min.css" var="bootstrapCss" /> - <link href="${bootstrapCss}" rel="stylesheet"/> - - <spring:url value="/resources/css/petclinic.css" var="petclinicCss" /> - <link href="${petclinicCss}" rel="stylesheet"/> - - <spring:url value="/webjars/jquery/1.8.2/jquery.js" var="jQuery" /> - <script src="${jQuery}"></script> - - <spring:url value="/webjars/jquery-ui/1.9.1/js/jquery-ui-1.9.1.custom.js" var="jQueryUi" /> - <script src="${jQueryUi}"></script> - - <spring:url value="/webjars/jquery-ui/1.9.1/css/smoothness/jquery-ui-1.9.1.custom.css" var="jQueryUiCss" /> - <link href="${jQueryUiCss}" rel="stylesheet"></link> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> + <title>PetClinic :: a Spring Framework demonstration</title> + + + <spring:url value="/webjars/bootstrap/2.2.1/css/bootstrap.min.css" var="bootstrapCss"/> + <link href="${bootstrapCss}" rel="stylesheet"/> + + <spring:url value="/resources/css/petclinic.css" var="petclinicCss"/> + <link href="${petclinicCss}" rel="stylesheet"/> + + <spring:url value="/webjars/jquery/1.8.2/jquery.js" var="jQuery"/> + <script src="${jQuery}"></script> + + <spring:url value="/webjars/jquery-ui/1.9.1/js/jquery-ui-1.9.1.custom.js" var="jQueryUi"/> + <script src="${jQueryUi}"></script> + + <spring:url value="/webjars/jquery-ui/1.9.1/css/smoothness/jquery-ui-1.9.1.custom.css" var="jQueryUiCss"/> + <link href="${jQueryUiCss}" rel="stylesheet"></link> </head> diff --git a/src/main/webapp/WEB-INF/jsp/owners/createOrUpdateOwnerForm.jsp b/src/main/webapp/WEB-INF/jsp/owners/createOrUpdateOwnerForm.jsp index 043814eaa5706fabd980d6c1e53c013a0a19b15e..9179dbc3abdd7c12d7518ec45a650a115495d794 100644 --- a/src/main/webapp/WEB-INF/jsp/owners/createOrUpdateOwnerForm.jsp +++ b/src/main/webapp/WEB-INF/jsp/owners/createOrUpdateOwnerForm.jsp @@ -11,36 +11,36 @@ <jsp:include page="../fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp"/> - <c:choose> - <c:when test="${owner['new']}"><c:set var="method" value="post"/></c:when> - <c:otherwise><c:set var="method" value="put"/></c:otherwise> - </c:choose> - - <h2> - <c:if test="${owner['new']}">New </c:if> Owner - </h2> - <form:form modelAttribute="owner" method="${method}" class="form-horizontal" id="add-owner-form"> - <petclinic:inputField label="First Name" name="firstName" /> - <petclinic:inputField label="Last Name" name="lastName" /> - <petclinic:inputField label="Address" name="address" /> - <petclinic:inputField label="City" name="city" /> - <petclinic:inputField label="Telephone" name="telephone" /> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + <c:choose> + <c:when test="${owner['new']}"><c:set var="method" value="post"/></c:when> + <c:otherwise><c:set var="method" value="put"/></c:otherwise> + </c:choose> - <div class="form-actions"> - <c:choose> - <c:when test="${owner['new']}"> - <button type="submit">Add Owner</button> - </c:when> - <c:otherwise> - <button type="submit">Update Owner</button> - </c:otherwise> - </c:choose> - </div> - </form:form> - </div> - <jsp:include page="../fragments/footer.jsp"/> + <h2> + <c:if test="${owner['new']}">New </c:if> Owner + </h2> + <form:form modelAttribute="owner" method="${method}" class="form-horizontal" id="add-owner-form"> + <petclinic:inputField label="First Name" name="firstName"/> + <petclinic:inputField label="Last Name" name="lastName"/> + <petclinic:inputField label="Address" name="address"/> + <petclinic:inputField label="City" name="city"/> + <petclinic:inputField label="Telephone" name="telephone"/> + + <div class="form-actions"> + <c:choose> + <c:when test="${owner['new']}"> + <button type="submit">Add Owner</button> + </c:when> + <c:otherwise> + <button type="submit">Update Owner</button> + </c:otherwise> + </c:choose> + </div> + </form:form> +</div> +<jsp:include page="../fragments/footer.jsp"/> </body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/owners/findOwners.jsp b/src/main/webapp/WEB-INF/jsp/owners/findOwners.jsp index 4f86370fd9348d43062e284e19e26e03e587ca2b..cd2808c88ce3230882981fa95de66e83a90bbd29 100644 --- a/src/main/webapp/WEB-INF/jsp/owners/findOwners.jsp +++ b/src/main/webapp/WEB-INF/jsp/owners/findOwners.jsp @@ -8,31 +8,32 @@ <jsp:include page="../fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp"/> - - <h2>Find Owners</h2> - - <spring:url value="/owners.html" var="formUrl"/> - <form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get" class="form-horizontal" id="search-owner-form"> - <fieldset> - <div class="control-group" id="lastName"> - <label class="control-label">Last name </label> - <form:input path="lastName" size="30" maxlength="80"/> - <span class="help-inline"><form:errors path="*" /></span> - </div> - <div class="form-actions"> - <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="../fragments/footer.jsp"/> - - </div> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + + <h2>Find Owners</h2> + + <spring:url value="/owners.html" var="formUrl"/> + <form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get" class="form-horizontal" + id="search-owner-form"> + <fieldset> + <div class="control-group" id="lastName"> + <label class="control-label">Last name </label> + <form:input path="lastName" size="30" maxlength="80"/> + <span class="help-inline"><form:errors path="*"/></span> + </div> + <div class="form-actions"> + <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="../fragments/footer.jsp"/> + +</div> </body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/owners/ownerDetails.jsp b/src/main/webapp/WEB-INF/jsp/owners/ownerDetails.jsp index 00e40d50fe09aaa316b511b2146dfaa2f5df1197..97175553df38d092ffd7b285ab0205c378c13016 100644 --- a/src/main/webapp/WEB-INF/jsp/owners/ownerDetails.jsp +++ b/src/main/webapp/WEB-INF/jsp/owners/ownerDetails.jsp @@ -9,111 +9,111 @@ <jsp:include page="../fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp"/> - - <h2>Owner Information</h2> - - <table class="table table-striped" style="width:600px;"> - <tr> - <th>Name</th> - <td><b><c:out value="${owner.firstName} ${owner.lastName}"/></b></td> - </tr> - <tr> - <th>Address</th> - <td><c:out value="${owner.address}"/></td> - </tr> - <tr> - <th>City</th> - <td><c:out value="${owner.city}"/></td> - </tr> - <tr> - <th>Telephone </th> - <td><c:out value="${owner.telephone}"/></td> - </tr> - </table> - <table class="table-buttons"> - <tr> - <td colspan="2" align="center"> - <spring:url value="{ownerId}/edit.html" var="editUrl"> - <spring:param name="ownerId" value="${owner.id}" /> - </spring:url> - <a href="${fn:escapeXml(editUrl)}">Edit Owner</a> - </td> - <td> - <spring:url value="{ownerId}/pets/new.html" var="addUrl"> - <spring:param name="ownerId" value="${owner.id}" /> - </spring:url> - <a href="${fn:escapeXml(addUrl)}">Add New Pet</a> - </td> - </tr> - </table> - - <h2>Pets and Visits</h2> - - <c:forEach var="pet" items="${owner.pets}"> - <table class="table" style="width:600px;"> - <tr> - <td valign="top" style="width: 120px;"> - <dl class="dl-horizontal"> - <dt>Name</dt> - <dd><c:out value="${pet.name}"/></dd> - <dt>Birth Date</dt> - <dd><joda:format value="${pet.birthDate}" pattern="yyyy-MM-dd" /></dd> - <dt>Type</dt> - <dd><c:out value="${pet.type.name}"/></dd> - </dl> - </td> - <td valign="top"> - <table class="table-condensed"> - <thead> - <tr> - <th>Visit Date</th> - <th>Description</th> - </tr> - </thead> - <c:forEach var="visit" items="${pet.visits}"> - <tr> - <td><joda:format value="${visit.date}" pattern="yyyy-MM-dd"/></td> - <td><c:out value="${visit.description}"/></td> - </tr> - </c:forEach> - </table> - </td> - </tr> - </table> - <table class="table-buttons"> - <tr> - <td> - <spring:url value="/owners/{ownerId}/pets/{petId}/edit" var="petUrl"> - <spring:param name="ownerId" value="${owner.id}"/> - <spring:param name="petId" value="${pet.id}"/> - </spring:url> - <a href="${fn:escapeXml(petUrl)}">Edit Pet</a> - </td> - <td></td> - <td> - <spring:url value="/owners/{ownerId}/pets/{petId}/visits/new" var="visitUrl"> - <spring:param name="ownerId" value="${owner.id}"/> - <spring:param name="petId" value="${pet.id}"/> - </spring:url> - <a href="${fn:escapeXml(visitUrl)}">Add Visit</a> - </td> - <td></td> - <td> - <spring:url value="/owners/{ownerId}/pets/{petId}/visits.atom" var="feedUrl"> - <spring:param name="ownerId" value="${owner.id}"/> - <spring:param name="petId" value="${pet.id}"/> - </spring:url> - <a href="${fn:escapeXml(feedUrl)}" rel="alternate" type="application/atom+xml">Atom Feed</a> - </td> - </tr> - </table> - </c:forEach> - - <jsp:include page="../fragments/footer.jsp"/> - - </div> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + + <h2>Owner Information</h2> + + <table class="table table-striped" style="width:600px;"> + <tr> + <th>Name</th> + <td><b><c:out value="${owner.firstName} ${owner.lastName}"/></b></td> + </tr> + <tr> + <th>Address</th> + <td><c:out value="${owner.address}"/></td> + </tr> + <tr> + <th>City</th> + <td><c:out value="${owner.city}"/></td> + </tr> + <tr> + <th>Telephone</th> + <td><c:out value="${owner.telephone}"/></td> + </tr> + </table> + <table class="table-buttons"> + <tr> + <td colspan="2" align="center"> + <spring:url value="{ownerId}/edit.html" var="editUrl"> + <spring:param name="ownerId" value="${owner.id}"/> + </spring:url> + <a href="${fn:escapeXml(editUrl)}">Edit Owner</a> + </td> + <td> + <spring:url value="{ownerId}/pets/new.html" var="addUrl"> + <spring:param name="ownerId" value="${owner.id}"/> + </spring:url> + <a href="${fn:escapeXml(addUrl)}">Add New Pet</a> + </td> + </tr> + </table> + + <h2>Pets and Visits</h2> + + <c:forEach var="pet" items="${owner.pets}"> + <table class="table" style="width:600px;"> + <tr> + <td valign="top" style="width: 120px;"> + <dl class="dl-horizontal"> + <dt>Name</dt> + <dd><c:out value="${pet.name}"/></dd> + <dt>Birth Date</dt> + <dd><joda:format value="${pet.birthDate}" pattern="yyyy-MM-dd"/></dd> + <dt>Type</dt> + <dd><c:out value="${pet.type.name}"/></dd> + </dl> + </td> + <td valign="top"> + <table class="table-condensed"> + <thead> + <tr> + <th>Visit Date</th> + <th>Description</th> + </tr> + </thead> + <c:forEach var="visit" items="${pet.visits}"> + <tr> + <td><joda:format value="${visit.date}" pattern="yyyy-MM-dd"/></td> + <td><c:out value="${visit.description}"/></td> + </tr> + </c:forEach> + </table> + </td> + </tr> + </table> + <table class="table-buttons"> + <tr> + <td> + <spring:url value="/owners/{ownerId}/pets/{petId}/edit" var="petUrl"> + <spring:param name="ownerId" value="${owner.id}"/> + <spring:param name="petId" value="${pet.id}"/> + </spring:url> + <a href="${fn:escapeXml(petUrl)}">Edit Pet</a> + </td> + <td></td> + <td> + <spring:url value="/owners/{ownerId}/pets/{petId}/visits/new" var="visitUrl"> + <spring:param name="ownerId" value="${owner.id}"/> + <spring:param name="petId" value="${pet.id}"/> + </spring:url> + <a href="${fn:escapeXml(visitUrl)}">Add Visit</a> + </td> + <td></td> + <td> + <spring:url value="/owners/{ownerId}/pets/{petId}/visits.atom" var="feedUrl"> + <spring:param name="ownerId" value="${owner.id}"/> + <spring:param name="petId" value="${pet.id}"/> + </spring:url> + <a href="${fn:escapeXml(feedUrl)}" rel="alternate" type="application/atom+xml">Atom Feed</a> + </td> + </tr> + </table> + </c:forEach> + + <jsp:include page="../fragments/footer.jsp"/> + +</div> </body> diff --git a/src/main/webapp/WEB-INF/jsp/owners/ownersList.jsp b/src/main/webapp/WEB-INF/jsp/owners/ownersList.jsp index 53145ecc30686835df64f67f04c09a02e20ad0c2..03f785821b7f0dd0e66840bbc69ada5ef5f1eef9 100644 --- a/src/main/webapp/WEB-INF/jsp/owners/ownersList.jsp +++ b/src/main/webapp/WEB-INF/jsp/owners/ownersList.jsp @@ -9,42 +9,42 @@ <jsp:include page="../fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp"/> - <h2>Owners</h2> - - <table class="table table-striped"> - <thead> - <tr> - <th style="width: 150px;">Name</th> - <th style="width: 200px;">Address</th> - <th>City</th> - <th>Telephone</th> - <th style="width: 100px;">Pets</th> - </tr> - </thead> - <c:forEach var="owner" items="${selections}"> - <tr> - <td> - <spring:url value="owners/{ownerId}.html" var="ownerUrl"> - <spring:param name="ownerId" value="${owner.id}"/> - </spring:url> - <a href="${fn:escapeXml(ownerUrl)}"><c:out value="${owner.firstName} ${owner.lastName}" /></a> - </td> - <td><c:out value="${owner.address}"/></td> - <td><c:out value="${owner.city}"/></td> - <td><c:out value="${owner.telephone}"/></td> - <td> - <c:forEach var="pet" items="${owner.pets}"> - <c:out value="${pet.name}"/> - </c:forEach> - </td> - </tr> - </c:forEach> - </table> - <jsp:include page="../fragments/footer.jsp"/> - - </div> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + <h2>Owners</h2> + + <table class="table table-striped"> + <thead> + <tr> + <th style="width: 150px;">Name</th> + <th style="width: 200px;">Address</th> + <th>City</th> + <th>Telephone</th> + <th style="width: 100px;">Pets</th> + </tr> + </thead> + <c:forEach var="owner" items="${selections}"> + <tr> + <td> + <spring:url value="owners/{ownerId}.html" var="ownerUrl"> + <spring:param name="ownerId" value="${owner.id}"/> + </spring:url> + <a href="${fn:escapeXml(ownerUrl)}"><c:out value="${owner.firstName} ${owner.lastName}"/></a> + </td> + <td><c:out value="${owner.address}"/></td> + <td><c:out value="${owner.city}"/></td> + <td><c:out value="${owner.telephone}"/></td> + <td> + <c:forEach var="pet" items="${owner.pets}"> + <c:out value="${pet.name}"/> + </c:forEach> + </td> + </tr> + </c:forEach> + </table> + <jsp:include page="../fragments/footer.jsp"/> + +</div> </body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/pets/createOrUpdatePetForm.jsp b/src/main/webapp/WEB-INF/jsp/pets/createOrUpdatePetForm.jsp index 8e114c3effa021804cf7b7a1835826190c414036..c33986abf1bc493a4fdcfad222df0e2ef8167404 100644 --- a/src/main/webapp/WEB-INF/jsp/pets/createOrUpdatePetForm.jsp +++ b/src/main/webapp/WEB-INF/jsp/pets/createOrUpdatePetForm.jsp @@ -1,6 +1,6 @@ -<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="petclinic" tagdir="/WEB-INF/tags" %> @@ -10,54 +10,54 @@ <body> <script> - $(function() { - $("#birthDate").datepicker({ dateFormat: 'yy/mm/dd'}); - }); + $(function () { + $("#birthDate").datepicker({ dateFormat: 'yy/mm/dd'}); + }); </script> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp" /> - <c:choose> - <c:when test="${pet['new']}"> - <c:set var="method" value="post" /> - </c:when> - <c:otherwise> - <c:set var="method" value="put" /> - </c:otherwise> - </c:choose> - - <h2> - <c:if test="${pet['new']}">New </c:if> - Pet - </h2> - - <form:form modelAttribute="pet" method="${method}" - class="form-horizontal"> - <div class="control-group" id="owner"> - <label class="control-label">Owner </label> - - <c:out value="${pet.owner.firstName} ${pet.owner.lastName}"/> - </div> - <petclinic:inputField label="Name" name="name" /> - <petclinic:inputField label="Birth Date" name="birthDate" /> - <div class="control-group"> - <label class="control-label">Type </label> - <form:select path="type" items="${types}" size="5"/> - </div> - <div class="form-actions"> - <c:choose> - <c:when test="${pet['new']}"> - <button type="submit">Add Pet</button> - </c:when> - <c:otherwise> - <button type="submit">Update Pet</button> - </c:otherwise> - </c:choose> - </div> - </form:form> - <c:if test="${!pet['new']}"> - </c:if> - <jsp:include page="../fragments/footer.jsp" /> - </div> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + <c:choose> + <c:when test="${pet['new']}"> + <c:set var="method" value="post"/> + </c:when> + <c:otherwise> + <c:set var="method" value="put"/> + </c:otherwise> + </c:choose> + + <h2> + <c:if test="${pet['new']}">New </c:if> + Pet + </h2> + + <form:form modelAttribute="pet" method="${method}" + class="form-horizontal"> + <div class="control-group" id="owner"> + <label class="control-label">Owner </label> + + <c:out value="${pet.owner.firstName} ${pet.owner.lastName}"/> + </div> + <petclinic:inputField label="Name" name="name"/> + <petclinic:inputField label="Birth Date" name="birthDate"/> + <div class="control-group"> + <label class="control-label">Type </label> + <form:select path="type" items="${types}" size="5"/> + </div> + <div class="form-actions"> + <c:choose> + <c:when test="${pet['new']}"> + <button type="submit">Add Pet</button> + </c:when> + <c:otherwise> + <button type="submit">Update Pet</button> + </c:otherwise> + </c:choose> + </div> + </form:form> + <c:if test="${!pet['new']}"> + </c:if> + <jsp:include page="../fragments/footer.jsp"/> +</div> </body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/pets/createOrUpdateVisitForm.jsp b/src/main/webapp/WEB-INF/jsp/pets/createOrUpdateVisitForm.jsp index 80f7f0d0a464c28bb7a5a6b7a9516e0e22faa3cd..e1c8a052d6e7300df70c8692a63d6cd14aa55844 100644 --- a/src/main/webapp/WEB-INF/jsp/pets/createOrUpdateVisitForm.jsp +++ b/src/main/webapp/WEB-INF/jsp/pets/createOrUpdateVisitForm.jsp @@ -10,73 +10,75 @@ <body> - <script> - $(function() { - $("#date").datepicker({ dateFormat: 'yy/mm/dd'}); - }); - </script> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp"/> - <h2><c:if test="${visit['new']}">New </c:if>Visit</h2> - - <b>Pet</b> - <table class="table table-striped"> - <thead> - <tr> - <th>Name</th> - <th>Birth Date</th> - <th>Type</th> - <th>Owner</th> - </tr> - </thead> - <tr> - <td><c:out value="${visit.pet.name}" /></td> - <td><joda:format value="${visit.pet.birthDate}" pattern="yyyy/MM/dd"/></td> - <td><c:out value="${visit.pet.type.name}" /></td> - <td><c:out value="${visit.pet.owner.firstName} ${visit.pet.owner.lastName}" /></td> - </tr> - </table> - - <form:form modelAttribute="visit"> - <div class="control-group"> - <label class="control-label">Date </label> - <div class="controls"> - <form:input path="date" /> - <span class="help-inline"><form:errors path="date" /></span> - </div> - </div> - <div class="control-group"> - <label class="control-label">Description </label> - <div class="controls"> - <form:input path="description" /> - <span class="help-inline"><form:errors path="description" /></span> - </div> - </div> - <div class="form-actions"> - <input type="hidden" name="petId" value="${visit.pet.id}"/> - <button type="submit">Add Visit</button> - </div> - </form:form> - - <br/> - <b>Previous Visits</b> - <table style="width: 333px;"> - <tr> - <th>Date</th> - <th>Description</th> - </tr> - <c:forEach var="visit" items="${visit.pet.visits}"> - <c:if test="${!visit['new']}"> - <tr> - <td><joda:format value="${visit.date}" pattern="yyyy/MM/dd"/></td> - <td><c:out value="${visit.description}" /></td> - </tr> - </c:if> - </c:forEach> - </table> +<script> + $(function () { + $("#date").datepicker({ dateFormat: 'yy/mm/dd'}); + }); +</script> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + <h2><c:if test="${visit['new']}">New </c:if>Visit</h2> - </div> - <jsp:include page="../fragments/footer.jsp"/> + <b>Pet</b> + <table class="table table-striped"> + <thead> + <tr> + <th>Name</th> + <th>Birth Date</th> + <th>Type</th> + <th>Owner</th> + </tr> + </thead> + <tr> + <td><c:out value="${visit.pet.name}"/></td> + <td><joda:format value="${visit.pet.birthDate}" pattern="yyyy/MM/dd"/></td> + <td><c:out value="${visit.pet.type.name}"/></td> + <td><c:out value="${visit.pet.owner.firstName} ${visit.pet.owner.lastName}"/></td> + </tr> + </table> + + <form:form modelAttribute="visit"> + <div class="control-group"> + <label class="control-label">Date </label> + + <div class="controls"> + <form:input path="date"/> + <span class="help-inline"><form:errors path="date"/></span> + </div> + </div> + <div class="control-group"> + <label class="control-label">Description </label> + + <div class="controls"> + <form:input path="description"/> + <span class="help-inline"><form:errors path="description"/></span> + </div> + </div> + <div class="form-actions"> + <input type="hidden" name="petId" value="${visit.pet.id}"/> + <button type="submit">Add Visit</button> + </div> + </form:form> + + <br/> + <b>Previous Visits</b> + <table style="width: 333px;"> + <tr> + <th>Date</th> + <th>Description</th> + </tr> + <c:forEach var="visit" items="${visit.pet.visits}"> + <c:if test="${!visit['new']}"> + <tr> + <td><joda:format value="${visit.date}" pattern="yyyy/MM/dd"/></td> + <td><c:out value="${visit.description}"/></td> + </tr> + </c:if> + </c:forEach> + </table> + +</div> +<jsp:include page="../fragments/footer.jsp"/> </body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/vets/vetList.jsp b/src/main/webapp/WEB-INF/jsp/vets/vetList.jsp index 54bb103564e2e8979a5e5035d111c2346d3ac769..4adaa14dbb929a1791c1f7c5ecf6c603e0411b37 100644 --- a/src/main/webapp/WEB-INF/jsp/vets/vetList.jsp +++ b/src/main/webapp/WEB-INF/jsp/vets/vetList.jsp @@ -9,45 +9,45 @@ <jsp:include page="../fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="../fragments/bodyHeader.jsp"/> - - <h2>Veterinarians</h2> - - <table class="table table-stripped" style="width:600px;"> - <thead> - <tr> - <th>Name</th> - <th>Specialties</th> - </tr> - </thead> - <tbody> - <c:forEach var="vet" items="${vets.vetList}"> - <tr> - <td><c:out value="${vet.firstName} ${vet.lastName}" /></td> - <td> - <c:forEach var="specialty" items="${vet.specialties}"> - <c:out value="${specialty.name}" /> - </c:forEach> - <c:if test="${vet.nrOfSpecialties == 0}">none</c:if> - </td> - </tr> - </c:forEach> - </tbody> - </table> - <table class="table-buttons"> - <tr> - <td> - <a href="<spring:url value="/vets.xml" htmlEscape="true" />">View as XML</a> - </td> - <td> - <a href="<spring:url value="/vets.atom" htmlEscape="true" />">Subscribe to Atom feed</a> - </td> - </tr> - </table> - - <jsp:include page="../fragments/footer.jsp"/> - </div> - </body> +<div class="container"> + <jsp:include page="../fragments/bodyHeader.jsp"/> + + <h2>Veterinarians</h2> + + <table class="table table-stripped" style="width:600px;"> + <thead> + <tr> + <th>Name</th> + <th>Specialties</th> + </tr> + </thead> + <tbody> + <c:forEach var="vet" items="${vets.vetList}"> + <tr> + <td><c:out value="${vet.firstName} ${vet.lastName}"/></td> + <td> + <c:forEach var="specialty" items="${vet.specialties}"> + <c:out value="${specialty.name}"/> + </c:forEach> + <c:if test="${vet.nrOfSpecialties == 0}">none</c:if> + </td> + </tr> + </c:forEach> + </tbody> + </table> + <table class="table-buttons"> + <tr> + <td> + <a href="<spring:url value="/vets.xml" htmlEscape="true" />">View as XML</a> + </td> + <td> + <a href="<spring:url value="/vets.atom" htmlEscape="true" />">Subscribe to Atom feed</a> + </td> + </tr> + </table> + + <jsp:include page="../fragments/footer.jsp"/> +</div> +</body> </html> diff --git a/src/main/webapp/WEB-INF/jsp/welcome.jsp b/src/main/webapp/WEB-INF/jsp/welcome.jsp index ab7de63aaade3e55526b6308ab0932e71b48c0d5..12c9f2c716a0b2a7cac7d6f23f7cf23b0994fc6e 100644 --- a/src/main/webapp/WEB-INF/jsp/welcome.jsp +++ b/src/main/webapp/WEB-INF/jsp/welcome.jsp @@ -7,15 +7,15 @@ <jsp:include page="fragments/headTag.jsp"/> <body> - <div class="container"> - <jsp:include page="fragments/bodyHeader.jsp"/> - <h2><fmt:message key="welcome"/></h2> - <spring:url value="/resources/images/pets.png" htmlEscape="true" var="petsImage"/> - <img src="${petsImage}" /> - - <jsp:include page="fragments/footer.jsp"/> +<div class="container"> + <jsp:include page="fragments/bodyHeader.jsp"/> + <h2><fmt:message key="welcome"/></h2> + <spring:url value="/resources/images/pets.png" htmlEscape="true" var="petsImage"/> + <img src="${petsImage}"/> - </div> + <jsp:include page="fragments/footer.jsp"/> + +</div> </body> </html> diff --git a/src/main/webapp/WEB-INF/tags/inputField.tag b/src/main/webapp/WEB-INF/tags/inputField.tag index f70cf36e1d9e81a70f04aa2bbbae98329d23e222..796dc91c04e991a431573f358739b26dfa6655ba 100644 --- a/src/main/webapp/WEB-INF/tags/inputField.tag +++ b/src/main/webapp/WEB-INF/tags/inputField.tag @@ -1,16 +1,19 @@ <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> -<%@ attribute name="name" required="true" rtexprvalue="true" description="Name of corresponding property in bean object"%> -<%@ attribute name="label" required="true" rtexprvalue="true" description="Label appears in red color if input is considered as invalid after submission"%> +<%@ attribute name="name" required="true" rtexprvalue="true" + description="Name of corresponding property in bean object" %> +<%@ attribute name="label" required="true" rtexprvalue="true" + description="Label appears in red color if input is considered as invalid after submission" %> <spring:bind path="${name}"> - <c:set var="cssGroup" value="control-group ${status.error ? 'error' : '' }"/> - <div class="${cssGroup}"> - <label class="control-label">${label}</label> - <div class="controls"> - <form:input path="${name}"/> - <span class="help-inline">${status.errorMessage}</span> - </div> - </div> + <c:set var="cssGroup" value="control-group ${status.error ? 'error' : '' }"/> + <div class="${cssGroup}"> + <label class="control-label">${label}</label> + + <div class="controls"> + <form:input path="${name}"/> + <span class="help-inline">${status.errorMessage}</span> + </div> + </div> </spring:bind> \ No newline at end of file diff --git a/src/main/webapp/resources/css/petclinic.css b/src/main/webapp/resources/css/petclinic.css index 590cbe06ea239339c47a7add54078ce4541245c5..36ad67082f6991efe878779d9d42c0dc59999291 100644 --- a/src/main/webapp/resources/css/petclinic.css +++ b/src/main/webapp/resources/css/petclinic.css @@ -1,21 +1,21 @@ .container { - padding-top: 10px; - margin-left: 50px; - width: 700px; + padding-top: 10px; + margin-left: 50px; + width: 700px; } .form-horizontal { - width: 100%; + width: 100%; } input[type="text"] { - height: 25px; + height: 25px; } .navbar .nav > li > a { - color: #000000; + color: #000000; } - .form-horizontal .control-label { +.form-horizontal .control-label { text-align: left; } diff --git a/src/test/java/org/springframework/samples/petclinic/model/OwnerTests.java b/src/test/java/org/springframework/samples/petclinic/model/OwnerTests.java index 9c64e3778f09a9a985d6ad0182f801cc743b1b2d..2eba3d997a313a11b08ebab00ecbee9c715769a8 100644 --- a/src/test/java/org/springframework/samples/petclinic/model/OwnerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/model/OwnerTests.java @@ -15,14 +15,12 @@ */ package org.springframework.samples.petclinic.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import org.junit.Test; -import org.springframework.samples.petclinic.model.Owner; -import org.springframework.samples.petclinic.model.Pet; import org.springframework.transaction.annotation.Transactional; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + /** * JUnit test for the {@link Owner} class. * @@ -30,16 +28,17 @@ import org.springframework.transaction.annotation.Transactional; */ public class OwnerTests { - @Test @Transactional - public void testHasPet() { - Owner owner = new Owner(); - Pet fido = new Pet(); - fido.setName("Fido"); - assertNull(owner.getPet("Fido")); - assertNull(owner.getPet("fido")); - owner.addPet(fido); - assertEquals(fido, owner.getPet("Fido")); - assertEquals(fido, owner.getPet("fido")); - } + @Test + @Transactional + public void testHasPet() { + Owner owner = new Owner(); + Pet fido = new Pet(); + fido.setName("Fido"); + assertNull(owner.getPet("Fido")); + assertNull(owner.getPet("fido")); + owner.addPet(fido); + assertEquals(fido, owner.getPet("Fido")); + assertEquals(fido, owner.getPet("fido")); + } } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/AbstractOwnerRepositoryTests.java b/src/test/java/org/springframework/samples/petclinic/repository/AbstractOwnerRepositoryTests.java index f9752c82caf264599e78fd32b71ed58c4514e1c1..e8330dfcb3c995f9bea13be82638388f6ad51b0c 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/AbstractOwnerRepositoryTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/AbstractOwnerRepositoryTests.java @@ -15,44 +15,29 @@ */ package org.springframework.samples.petclinic.repository; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; - import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Owner; -import org.springframework.samples.petclinic.repository.OwnerRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** - * <p> - * Base class for {@link OwnerRepository} integration tests. - * </p> - * <p> - * Subclasses should specify Spring context configuration using {@link ContextConfiguration @ContextConfiguration} annotation - * </p> - * <p> - * AbstractOwnerRepositoryTests and its subclasses benefit from the following services - * provided by the Spring TestContext Framework: - * </p> - * <ul> - * <li><strong>Spring IoC container caching</strong> which spares us - * unnecessary set up time between test execution.</li> - * <li><strong>Dependency Injection</strong> of test fixture instances, - * meaning that we don't need to perform application context lookups. See the - * use of {@link Autowired @Autowired} on the <code>{@link AbstractOwnerRepositoryTests#ownerRepository ownerRepository}</code> instance - * variable, which uses autowiring <em>by type</em>. - * <li><strong>Transaction management</strong>, meaning each test method is - * executed in its own transaction, which is automatically rolled back by - * default. Thus, even if tests insert or otherwise change database state, there - * is no need for a teardown or cleanup script. - * <li> An {@link org.springframework.context.ApplicationContext ApplicationContext} is - * also inherited and can be used for explicit bean lookup if necessary. - * </li> - * </ul> + * <p> Base class for {@link OwnerRepository} integration tests. </p> <p> Subclasses should specify Spring context + * configuration using {@link ContextConfiguration @ContextConfiguration} annotation </p> <p> + * AbstractOwnerRepositoryTests and its subclasses benefit from the following services provided by the Spring + * TestContext Framework: </p> <ul> <li><strong>Spring IoC container caching</strong> which spares us unnecessary set up + * time between test execution.</li> <li><strong>Dependency Injection</strong> of test fixture instances, meaning that + * we don't need to perform application context lookups. See the use of {@link Autowired @Autowired} on the <code>{@link + * AbstractOwnerRepositoryTests#ownerRepository ownerRepository}</code> instance variable, which uses autowiring <em>by + * type</em>. <li><strong>Transaction management</strong>, meaning each test method is executed in its own transaction, + * which is automatically rolled back by default. Thus, even if tests insert or otherwise change database state, there + * is no need for a teardown or cleanup script. <li> An {@link org.springframework.context.ApplicationContext + * ApplicationContext} is also inherited and can be used for explicit bean lookup if necessary. </li> </ul> * * @author Ken Krebs * @author Rod Johnson @@ -62,52 +47,55 @@ import org.springframework.transaction.annotation.Transactional; */ public abstract class AbstractOwnerRepositoryTests { - @Autowired - protected OwnerRepository ownerRepository; - - @Test @Transactional - public void findOwners() { - Collection<Owner> owners = this.ownerRepository.findByLastName("Davis"); - assertEquals(2, owners.size()); - owners = this.ownerRepository.findByLastName("Daviss"); - assertEquals(0, owners.size()); - } + @Autowired + protected OwnerRepository ownerRepository; - @Test @Transactional - public void findSingleOwner() { - Owner owner1 = this.ownerRepository.findById(1); - assertTrue(owner1.getLastName().startsWith("Franklin")); - Owner owner10 = this.ownerRepository.findById(10); - assertEquals("Carlos", owner10.getFirstName()); + @Test + @Transactional + public void findOwners() { + Collection<Owner> owners = this.ownerRepository.findByLastName("Davis"); + assertEquals(2, owners.size()); + owners = this.ownerRepository.findByLastName("Daviss"); + assertEquals(0, owners.size()); + } - assertEquals(owner1.getPets().size(), 1); - } + @Test + @Transactional + public void findSingleOwner() { + Owner owner1 = this.ownerRepository.findById(1); + assertTrue(owner1.getLastName().startsWith("Franklin")); + Owner owner10 = this.ownerRepository.findById(10); + assertEquals("Carlos", owner10.getFirstName()); - @Test @Transactional - public void insertOwner() { - Collection<Owner> owners = this.ownerRepository.findByLastName("Schultz"); - int found = owners.size(); - Owner owner = new Owner(); - owner.setFirstName("Sam"); - owner.setLastName("Schultz"); - owner.setAddress("4, Evans Street"); - owner.setCity("Wollongong"); - owner.setTelephone("4444444444"); - this.ownerRepository.save(owner); - owners = this.ownerRepository.findByLastName("Schultz"); - assertEquals("Verifying number of owners after inserting a new one.", found + 1, owners.size()); - } + assertEquals(owner1.getPets().size(), 1); + } - @Test @Transactional - public void updateOwner() throws Exception { - Owner o1 = this.ownerRepository.findById(1); - String old = o1.getLastName(); - o1.setLastName(old + "X"); - this.ownerRepository.save(o1); - o1 = this.ownerRepository.findById(1); - assertEquals(old + "X", o1.getLastName()); - } + @Test + @Transactional + public void insertOwner() { + Collection<Owner> owners = this.ownerRepository.findByLastName("Schultz"); + int found = owners.size(); + Owner owner = new Owner(); + owner.setFirstName("Sam"); + owner.setLastName("Schultz"); + owner.setAddress("4, Evans Street"); + owner.setCity("Wollongong"); + owner.setTelephone("4444444444"); + this.ownerRepository.save(owner); + owners = this.ownerRepository.findByLastName("Schultz"); + assertEquals("Verifying number of owners after inserting a new one.", found + 1, owners.size()); + } + @Test + @Transactional + public void updateOwner() throws Exception { + Owner o1 = this.ownerRepository.findById(1); + String old = o1.getLastName(); + o1.setLastName(old + "X"); + this.ownerRepository.save(o1); + o1 = this.ownerRepository.findById(1); + assertEquals(old + "X", o1.getLastName()); + } } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/AbstractPetRepositoryTests.java b/src/test/java/org/springframework/samples/petclinic/repository/AbstractPetRepositoryTests.java index 7a565aca659ce81af56972aaf30c2e3407446526..691e07aba4212a199fab315393fd76b39d9321a4 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/AbstractPetRepositoryTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/AbstractPetRepositoryTests.java @@ -15,27 +15,23 @@ */ package org.springframework.samples.petclinic.repository; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; - import org.joda.time.DateTime; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Owner; import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; -import org.springframework.samples.petclinic.repository.OwnerRepository; -import org.springframework.samples.petclinic.repository.PetRepository; import org.springframework.samples.petclinic.util.EntityUtils; import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** - * <p> - * Base class for {@link OwnerRepository} integration tests. - * </p> - * <p> + * <p> Base class for {@link OwnerRepository} integration tests. </p> + * <p/> * see javadoc inside {@link AbstractOwnerRepositoryTests} for more details * * @author Ken Krebs @@ -46,62 +42,66 @@ import org.springframework.transaction.annotation.Transactional; */ public abstract class AbstractPetRepositoryTests { - @Autowired - protected PetRepository petRepository; - - @Autowired - protected OwnerRepository ownerRepository; + @Autowired + protected PetRepository petRepository; + + @Autowired + protected OwnerRepository ownerRepository; + + @Test + @Transactional + public void getPetTypes() { + Collection<PetType> petTypes = this.petRepository.findPetTypes(); - @Test @Transactional - public void getPetTypes() { - Collection<PetType> petTypes = this.petRepository.findPetTypes(); - - PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1); - assertEquals("cat", petType1.getName()); - PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4); - assertEquals("snake", petType4.getName()); - } + PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1); + assertEquals("cat", petType1.getName()); + PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4); + assertEquals("snake", petType4.getName()); + } - @Test @Transactional - public void findPet() { - Collection<PetType> types = this.petRepository.findPetTypes(); - Pet pet7 = this.petRepository.findById(7); - assertTrue(pet7.getName().startsWith("Samantha")); - assertEquals(EntityUtils.getById(types, PetType.class, 1).getId(), pet7.getType().getId()); - assertEquals("Jean", pet7.getOwner().getFirstName()); - Pet pet6 = this.petRepository.findById(6); - assertEquals("George", pet6.getName()); - assertEquals(EntityUtils.getById(types, PetType.class, 4).getId(), pet6.getType().getId()); - assertEquals("Peter", pet6.getOwner().getFirstName()); - } + @Test + @Transactional + public void findPet() { + Collection<PetType> types = this.petRepository.findPetTypes(); + Pet pet7 = this.petRepository.findById(7); + assertTrue(pet7.getName().startsWith("Samantha")); + assertEquals(EntityUtils.getById(types, PetType.class, 1).getId(), pet7.getType().getId()); + assertEquals("Jean", pet7.getOwner().getFirstName()); + Pet pet6 = this.petRepository.findById(6); + assertEquals("George", pet6.getName()); + assertEquals(EntityUtils.getById(types, PetType.class, 4).getId(), pet6.getType().getId()); + assertEquals("Peter", pet6.getOwner().getFirstName()); + } - @Test @Transactional - public void insertPet() { - Owner owner6 = this.ownerRepository.findById(6); - int found = owner6.getPets().size(); - Pet pet = new Pet(); - pet.setName("bowser"); - Collection<PetType> types = this.petRepository.findPetTypes(); - pet.setType(EntityUtils.getById(types, PetType.class, 2)); - pet.setBirthDate(new DateTime()); - owner6.addPet(pet); - assertEquals(found + 1, owner6.getPets().size()); - // both storePet and storeOwner are necessary to cover all ORM tools - this.petRepository.save(pet); - this.ownerRepository.save(owner6); - owner6 = this.ownerRepository.findById(6); - assertEquals(found + 1, owner6.getPets().size()); - } + @Test + @Transactional + public void insertPet() { + Owner owner6 = this.ownerRepository.findById(6); + int found = owner6.getPets().size(); + Pet pet = new Pet(); + pet.setName("bowser"); + Collection<PetType> types = this.petRepository.findPetTypes(); + pet.setType(EntityUtils.getById(types, PetType.class, 2)); + pet.setBirthDate(new DateTime()); + owner6.addPet(pet); + assertEquals(found + 1, owner6.getPets().size()); + // both storePet and storeOwner are necessary to cover all ORM tools + this.petRepository.save(pet); + this.ownerRepository.save(owner6); + owner6 = this.ownerRepository.findById(6); + assertEquals(found + 1, owner6.getPets().size()); + } - @Test @Transactional - public void updatePet() throws Exception { - Pet pet7 = this.petRepository.findById(7); - String old = pet7.getName(); - pet7.setName(old + "X"); - this.petRepository.save(pet7); - pet7 = this.petRepository.findById(7); - assertEquals(old + "X", pet7.getName()); - } + @Test + @Transactional + public void updatePet() throws Exception { + Pet pet7 = this.petRepository.findById(7); + String old = pet7.getName(); + pet7.setName(old + "X"); + this.petRepository.save(pet7); + pet7 = this.petRepository.findById(7); + assertEquals(old + "X", pet7.getName()); + } } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/AbstractVetRepositoryTests.java b/src/test/java/org/springframework/samples/petclinic/repository/AbstractVetRepositoryTests.java index c17311c2880dafe195f605a46abbe8b5444a36fb..bd906ed55f60065f3abb2662e1873cd965426d52 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/AbstractVetRepositoryTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/AbstractVetRepositoryTests.java @@ -15,23 +15,19 @@ */ package org.springframework.samples.petclinic.repository; -import static org.junit.Assert.assertEquals; - -import java.util.Collection; - import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Vet; -import org.springframework.samples.petclinic.repository.OwnerRepository; -import org.springframework.samples.petclinic.repository.VetRepository; import org.springframework.samples.petclinic.util.EntityUtils; import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; + /** - * <p> - * Base class for {@link OwnerRepository} integration tests. - * </p> - * <p> + * <p> Base class for {@link OwnerRepository} integration tests. </p> + * <p/> * see javadoc inside {@link AbstractVetRepositoryTests} for more details * * @author Ken Krebs @@ -42,23 +38,24 @@ import org.springframework.transaction.annotation.Transactional; */ public abstract class AbstractVetRepositoryTests { - @Autowired - protected VetRepository vetRepository; - - - @Test @Transactional - public void findVets() { - Collection<Vet> vets = this.vetRepository.findAll(); - - Vet v1 = EntityUtils.getById(vets, Vet.class, 2); - assertEquals("Leary", v1.getLastName()); - assertEquals(1, v1.getNrOfSpecialties()); - assertEquals("radiology", (v1.getSpecialties().get(0)).getName()); - Vet v2 = EntityUtils.getById(vets, Vet.class, 3); - assertEquals("Douglas", v2.getLastName()); - assertEquals(2, v2.getNrOfSpecialties()); - assertEquals("dentistry", (v2.getSpecialties().get(0)).getName()); - assertEquals("surgery", (v2.getSpecialties().get(1)).getName()); - } + @Autowired + protected VetRepository vetRepository; + + + @Test + @Transactional + public void findVets() { + Collection<Vet> vets = this.vetRepository.findAll(); + + Vet v1 = EntityUtils.getById(vets, Vet.class, 2); + assertEquals("Leary", v1.getLastName()); + assertEquals(1, v1.getNrOfSpecialties()); + assertEquals("radiology", (v1.getSpecialties().get(0)).getName()); + Vet v2 = EntityUtils.getById(vets, Vet.class, 3); + assertEquals("Douglas", v2.getLastName()); + assertEquals(2, v2.getNrOfSpecialties()); + assertEquals("dentistry", (v2.getSpecialties().get(0)).getName()); + assertEquals("surgery", (v2.getSpecialties().get(1)).getName()); + } } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/AbstractVisitRepositoryTests.java b/src/test/java/org/springframework/samples/petclinic/repository/AbstractVisitRepositoryTests.java index 6ea8bbb981c43ff6ec9141501c2ee4b3569de1a6..59608789dcabcd591be50148e08ed8db4963a738 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/AbstractVisitRepositoryTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/AbstractVisitRepositoryTests.java @@ -15,22 +15,17 @@ */ package org.springframework.samples.petclinic.repository; -import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.Visit; -import org.springframework.samples.petclinic.repository.OwnerRepository; -import org.springframework.samples.petclinic.repository.PetRepository; -import org.springframework.samples.petclinic.repository.VisitRepository; import org.springframework.transaction.annotation.Transactional; +import static org.junit.Assert.assertEquals; + /** - * <p> - * Base class for {@link OwnerRepository} integration tests. - * </p> - * <p> + * <p> Base class for {@link OwnerRepository} integration tests. </p> + * <p/> * see javadoc inside {@link AbstractVetRepositoryTests} for more details * * @author Ken Krebs @@ -41,25 +36,26 @@ import org.springframework.transaction.annotation.Transactional; */ public abstract class AbstractVisitRepositoryTests { - @Autowired - protected VisitRepository visitRepository; - - @Autowired - protected PetRepository petRepository; + @Autowired + protected VisitRepository visitRepository; + + @Autowired + protected PetRepository petRepository; - @Test @Transactional - public void insertVisit() { - Pet pet7 = this.petRepository.findById(7); - int found = pet7.getVisits().size(); - Visit visit = new Visit(); - pet7.addVisit(visit); - visit.setDescription("test"); - // both storeVisit and storePet are necessary to cover all ORM tools - this.visitRepository.save(visit); - this.petRepository.save(pet7); - pet7 = this.petRepository.findById(7); - assertEquals(found + 1, pet7.getVisits().size()); - } + @Test + @Transactional + public void insertVisit() { + Pet pet7 = this.petRepository.findById(7); + int found = pet7.getVisits().size(); + Visit visit = new Visit(); + pet7.addVisit(visit); + visit.setDescription("test"); + // both storeVisit and storePet are necessary to cover all ORM tools + this.visitRepository.save(visit); + this.petRepository.save(pet7); + pet7 = this.petRepository.findById(7); + assertEquals(found + 1, pet7.getVisits().size()); + } } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImplTests.java index 6b074c95ad3548b4c0616411cf979cd0992ade56..fb6f1f8894d44c032b83c830957a4a44929a0829 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcOwnerRepositoryImplTests.java @@ -22,20 +22,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jdbc") public class JdbcOwnerRepositoryImplTests extends AbstractOwnerRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImplTests.java index c6d1434acefa393dee559b244d795ada0570b3e2..008818fc33718b25b5a18d01bcc0d9827b99de0f 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcPetRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jdbc") public class JdbcPetRepositoryImplTests extends AbstractPetRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImplTests.java index 86391486559bfbaf4b44c106e9624a1739b8988c..e2a4e8b7b00db8a19a1b35b1d8012727fb324903 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVetRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jdbc") public class JdbcVetRepositoryImplTests extends AbstractVetRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImplTests.java index 600e69c75b6ee531a90f745f95851d69f8ac1c63..6a349889296e261d01206797092d875fbccabaf8 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jdbc/JdbcVisitRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jdbc") public class JdbcVisitRepositoryImplTests extends AbstractVisitRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImplTests.java index a4e1348e0546897c21da212243a21982a651751b..2936515b000f54e33fe53e597b1a24bc146fa8b5 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaOwnerRepositoryImplTests.java @@ -8,27 +8,19 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Provides the following services: - * <ul> - * <li>Injects test dependencies, meaning that we don't need to perform - * application context lookups. See the setClinic() method. Injection uses - * autowiring by type.</li> - * <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> - * </ul> - * <p> - * </p> + * <p> Provides the following services: <ul> <li>Injects test dependencies, meaning that we don't need to perform + * application context lookups. See the setClinic() method. Injection uses autowiring by type.</li> <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> </ul> <p> </p> * * @author Rod Johnson * @author Sam Brannen * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jpa") public class JpaOwnerRepositoryImplTests extends AbstractOwnerRepositoryTests { - + } \ No newline at end of file diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImplTests.java index e09bf7ccdc6a3304ac395cac7038f6fcc6490c25..ec5b503377f04d3f185800fdbf112868dad5a066 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaPetRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jpa") public class JpaPetRepositoryImplTests extends AbstractPetRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImplTests.java index 635a482639197fea3ea3d5d029b77926c5fa1f89..433f34cc683131f875240f07aa8063b49905e022 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVetRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jpa") public class JpaVetRepositoryImplTests extends AbstractVetRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImplTests.java index 7e60adaec1a7db39a4cc2dd0ed5542c092b2b662..97e728a23365805617a76c08e63c1c5bcf9e42fa 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/jpa/JpaVisitRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jpa") public class JpaVisitRepositoryImplTests extends AbstractVisitRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImplTests.java index afd2cb40e58949928a2f7320de9e16c6f9086438..3130dc604078f7b17d2817aa992be32704b6706e 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaOwnerRepositoryImplTests.java @@ -8,27 +8,19 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Provides the following services: - * <ul> - * <li>Injects test dependencies, meaning that we don't need to perform - * application context lookups. See the setClinic() method. Injection uses - * autowiring by type.</li> - * <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> - * </ul> - * <p> - * </p> + * <p> Provides the following services: <ul> <li>Injects test dependencies, meaning that we don't need to perform + * application context lookups. See the setClinic() method. Injection uses autowiring by type.</li> <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> </ul> <p> </p> * * @author Rod Johnson * @author Sam Brannen * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("spring-data-jpa") public class JpaOwnerRepositoryImplTests extends AbstractOwnerRepositoryTests { - + } \ No newline at end of file diff --git a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaPetRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaPetRepositoryImplTests.java index ebcdbd965a70ddeb11bb723387f126860f87c7a2..842380d513169e299be9aecc3d741d8520c79364 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaPetRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaPetRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("spring-data-jpa") public class JpaPetRepositoryImplTests extends AbstractPetRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVetRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVetRepositoryImplTests.java index 84fdf99172e19da129091e494469f522f486542d..204cb6a7ba91830fe93a4d2bad1dc0699e48ab00 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVetRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVetRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("spring-data-jpa") public class JpaVetRepositoryImplTests extends AbstractVetRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVisitRepositoryImplTests.java b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVisitRepositoryImplTests.java index 146748a1d5a1a1aa46d4d0ccd067d3a365802875..0705700ae6641291149ff440033c1192f7a81052 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVisitRepositoryImplTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/JpaVisitRepositoryImplTests.java @@ -7,20 +7,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * <p> - * Integration tests for the {@link JdbcClinicImpl} implementation. - * </p> - * <p> - * </p> + * <p> Integration tests for the {@link JdbcClinicImpl} implementation. </p> <p> </p> * * @author Thomas Risberg - * @author Michael Isvy + * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("spring-data-jpa") public class JpaVisitRepositoryImplTests extends AbstractVisitRepositoryTests { - - + } diff --git a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataOwnerRepositoryTests.java b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataOwnerRepositoryTests.java index ba07be4b31e9197c8f8f382604bc7576287b2ba2..de53fa0489bb52f592423a296340fbe4be74d518 100644 --- a/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataOwnerRepositoryTests.java +++ b/src/test/java/org/springframework/samples/petclinic/repository/springdatajpa/SpringDataOwnerRepositoryTests.java @@ -11,9 +11,9 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Michael Isvy */ -@ContextConfiguration(locations={"classpath:spring/dao-config.xml"}) +@ContextConfiguration(locations = {"classpath:spring/dao-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("spring-data-jpa") public class SpringDataOwnerRepositoryTests extends AbstractOwnerRepositoryTests { - + } \ No newline at end of file diff --git a/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTest.java b/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTest.java index 90b52e0b33fabf08ecbeb3ddeff0018a158c846b..51458c86f0b34d63f7f3e501acd7072ebb2d7fcb 100644 --- a/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTest.java +++ b/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTest.java @@ -16,14 +16,8 @@ package org.springframework.samples.petclinic.web; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.sun.syndication.feed.atom.Entry; +import com.sun.syndication.feed.atom.Feed; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; @@ -31,63 +25,68 @@ import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.model.Visit; -import com.sun.syndication.feed.atom.Entry; -import com.sun.syndication.feed.atom.Feed; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; /** - * @author Arjen Poutsma + * @author Arjen Poutsma * @author Michael Isvy */ public class VisitsAtomViewTest { - private VetsAtomView visitView; - - private Map<String, Object> model; - - private Feed feed; - - @Before - public void setUp() { - visitView = new VetsAtomView(); - PetType dog = new PetType(); - dog.setName("dog"); - Pet bello = new Pet(); - bello.setName("Bello"); - bello.setType(dog); - Visit belloVisit = new Visit(); - belloVisit.setPet(bello); - belloVisit.setDate(new DateTime(2009, 1, 1, 1, 1)); - belloVisit.setDescription("Bello visit"); - Pet wodan = new Pet(); - wodan.setName("Wodan"); - wodan.setType(dog); - Visit wodanVisit = new Visit(); - wodanVisit.setPet(wodan); - wodanVisit.setDate(new DateTime(2009, 1, 2, 1, 1)); - wodanVisit.setDescription("Wodan visit"); - List<Visit> visits = new ArrayList<Visit>(); - visits.add(belloVisit); - visits.add(wodanVisit); - - model = new HashMap<String, Object>(); - model.put("visits", visits); - feed = new Feed(); - - } - - - @Test - public void buildFeedMetadata() { - visitView.buildFeedMetadata(model, feed, null); - - assertNotNull("No id set", feed.getId()); - assertNotNull("No title set", feed.getTitle()); - assertEquals("Invalid update set", new DateTime(2009, 1, 2, 1, 1).toDate(), feed.getUpdated()); - } - - @Test - public void buildFeedEntries() throws Exception { - List<Entry> entries = visitView.buildFeedEntries(model, null, null); - assertEquals("Invalid amount of entries", 2, entries.size()); - } + private VetsAtomView visitView; + + private Map<String, Object> model; + + private Feed feed; + + @Before + public void setUp() { + visitView = new VetsAtomView(); + PetType dog = new PetType(); + dog.setName("dog"); + Pet bello = new Pet(); + bello.setName("Bello"); + bello.setType(dog); + Visit belloVisit = new Visit(); + belloVisit.setPet(bello); + belloVisit.setDate(new DateTime(2009, 1, 1, 1, 1)); + belloVisit.setDescription("Bello visit"); + Pet wodan = new Pet(); + wodan.setName("Wodan"); + wodan.setType(dog); + Visit wodanVisit = new Visit(); + wodanVisit.setPet(wodan); + wodanVisit.setDate(new DateTime(2009, 1, 2, 1, 1)); + wodanVisit.setDescription("Wodan visit"); + List<Visit> visits = new ArrayList<Visit>(); + visits.add(belloVisit); + visits.add(wodanVisit); + + model = new HashMap<String, Object>(); + model.put("visits", visits); + feed = new Feed(); + + } + + + @Test + public void buildFeedMetadata() { + visitView.buildFeedMetadata(model, feed, null); + + assertNotNull("No id set", feed.getId()); + assertNotNull("No title set", feed.getTitle()); + assertEquals("Invalid update set", new DateTime(2009, 1, 2, 1, 1).toDate(), feed.getUpdated()); + } + + @Test + public void buildFeedEntries() throws Exception { + List<Entry> entries = visitView.buildFeedEntries(model, null, null); + assertEquals("Invalid amount of entries", 2, entries.size()); + } } diff --git a/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTestWithContainer-config.xml b/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTestWithContainer-config.xml index e0fd0acd02f2b7d0eb87db84adb9672323f8add1..75f913087391e261b2669b92780e584fd00aac86 100644 --- a/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTestWithContainer-config.xml +++ b/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewTestWithContainer-config.xml @@ -2,10 +2,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" - xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - - <import resource="classpath:spring/dao-config.xml"/> - <import resource="classpath:spring/mvc-core-config.xml"/> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd"> + + <import resource="classpath:spring/dao-config.xml"/> + <import resource="classpath:spring/mvc-core-config.xml"/> </beans> diff --git a/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewWithContainerTest.java b/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewWithContainerTest.java index 1cfcdcf88877fee27f9e75e2fb63ad55e55fff48..542c2ee4edcb576bf027b7220ff8d3235ad20621 100644 --- a/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewWithContainerTest.java +++ b/src/test/java/org/springframework/samples/petclinic/web/VisitsAtomViewWithContainerTest.java @@ -16,12 +16,6 @@ package org.springframework.samples.petclinic.web; -import static org.hamcrest.Matchers.containsString; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,8 +30,12 @@ import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + /** - * @author Arjen Poutsma + * @author Arjen Poutsma * @author Michael Isvy */ @RunWith(SpringJUnit4ClassRunner.class) @@ -48,23 +46,24 @@ import org.springframework.web.context.WebApplicationContext; @ActiveProfiles("jdbc") public class VisitsAtomViewWithContainerTest { - @Autowired - private WebApplicationContext webApplicationContext; + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); + } - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); - } + @Test + public void getVisits() throws Exception { + //gDickens: MediaType is not used + MediaType mediaType = MediaType.APPLICATION_ATOM_XML; + ResultActions actions = this.mockMvc.perform(get("/vets.atom")); + actions.andExpect(status().isOk()); + actions.andExpect(xpath("//*").string(containsString("Pet ClinicService Visits"))); + actions.andExpect(content().contentType("application/atom+xml")); - @Test - public void getVisits() throws Exception { - MediaType mediaType = MediaType.APPLICATION_ATOM_XML; - ResultActions actions = this.mockMvc.perform(get("/vets.atom")); - actions.andExpect(status().isOk()); - actions.andExpect(xpath("//*").string(containsString("Pet ClinicService Visits"))); - actions.andExpect(content().contentType("application/atom+xml")); - - } + } }