DATAJPA-98 - Formatted sources with Spring Data Eclipse formatting settings.
This commit is contained in:
@@ -19,12 +19,11 @@ import javax.persistence.Entity;
|
||||
|
||||
import org.springframework.data.jpa.domain.AbstractPersistable;
|
||||
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@Entity
|
||||
public class Account extends AbstractPersistable<Long> {
|
||||
|
||||
private static final long serialVersionUID = -5719129808165758887L;
|
||||
private static final long serialVersionUID = -5719129808165758887L;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import javax.persistence.Entity;
|
||||
|
||||
import org.springframework.data.jpa.domain.AbstractAuditable;
|
||||
|
||||
|
||||
/**
|
||||
* Sample auditable role entity.
|
||||
*
|
||||
@@ -28,19 +27,17 @@ import org.springframework.data.jpa.domain.AbstractAuditable;
|
||||
@Entity
|
||||
public class AuditableRole extends AbstractAuditable<AuditableUser, Long> {
|
||||
|
||||
private static final long serialVersionUID = 5997359055260303863L;
|
||||
private static final long serialVersionUID = 5997359055260303863L;
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
public void setName(String name) {
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
public String getName() {
|
||||
|
||||
|
||||
public String getName() {
|
||||
|
||||
return name;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,11 +25,9 @@ import javax.persistence.NamedQuery;
|
||||
|
||||
import org.springframework.data.jpa.domain.AbstractAuditable;
|
||||
|
||||
|
||||
/**
|
||||
* Sample auditable user to demonstrate working with
|
||||
* {@code AbstractAuditableEntity}. No declaration of an ID is necessary.
|
||||
* Furthermore no auditing information has to be declared explicitly.
|
||||
* Sample auditable user to demonstrate working with {@code AbstractAuditableEntity}. No declaration of an ID is
|
||||
* necessary. Furthermore no auditing information has to be declared explicitly.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@@ -37,56 +35,50 @@ import org.springframework.data.jpa.domain.AbstractAuditable;
|
||||
@NamedQuery(name = "AuditableUser.findByFirstname", query = "SELECT u FROM AuditableUser u WHERE u.firstname = ?1")
|
||||
public class AuditableUser extends AbstractAuditable<AuditableUser, Long> {
|
||||
|
||||
private static final long serialVersionUID = 7409344446795693011L;
|
||||
private static final long serialVersionUID = 7409344446795693011L;
|
||||
|
||||
private String firstname;
|
||||
private String firstname;
|
||||
|
||||
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
|
||||
private Set<AuditableRole> roles = new HashSet<AuditableRole>();
|
||||
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
|
||||
private Set<AuditableRole> roles = new HashSet<AuditableRole>();
|
||||
|
||||
public AuditableUser() {
|
||||
|
||||
public AuditableUser() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
this(null);
|
||||
}
|
||||
public AuditableUser(Long id) {
|
||||
|
||||
this.setId(id);
|
||||
}
|
||||
|
||||
public AuditableUser(Long id) {
|
||||
/**
|
||||
* Returns the firstname.
|
||||
*
|
||||
* @return the firstname
|
||||
*/
|
||||
public String getFirstname() {
|
||||
|
||||
this.setId(id);
|
||||
}
|
||||
return firstname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the firstname.
|
||||
*
|
||||
* @param firstname the firstname to set
|
||||
*/
|
||||
public void setFirstname(final String firstname) {
|
||||
|
||||
/**
|
||||
* Returns the firstname.
|
||||
*
|
||||
* @return the firstname
|
||||
*/
|
||||
public String getFirstname() {
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
return firstname;
|
||||
}
|
||||
public void addRole(AuditableRole role) {
|
||||
|
||||
this.roles.add(role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the firstname.
|
||||
*
|
||||
* @param firstname the firstname to set
|
||||
*/
|
||||
public void setFirstname(final String firstname) {
|
||||
public Set<AuditableRole> getRoles() {
|
||||
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
|
||||
public void addRole(AuditableRole role) {
|
||||
|
||||
this.roles.add(role);
|
||||
}
|
||||
|
||||
|
||||
public Set<AuditableRole> getRoles() {
|
||||
|
||||
return roles;
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,40 +19,35 @@ import org.springframework.data.domain.AuditorAware;
|
||||
import org.springframework.data.jpa.repository.sample.AuditableUserRepository;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* Stub implementation for {@link AuditorAware}. Returns {@literal null} for the
|
||||
* current auditor.
|
||||
* Stub implementation for {@link AuditorAware}. Returns {@literal null} for the current auditor.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AuditorAwareStub implements AuditorAware<AuditableUser> {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private final AuditableUserRepository repository;
|
||||
private AuditableUser auditor;
|
||||
@SuppressWarnings("unused")
|
||||
private final AuditableUserRepository repository;
|
||||
private AuditableUser auditor;
|
||||
|
||||
public AuditorAwareStub(AuditableUserRepository repository) {
|
||||
|
||||
public AuditorAwareStub(AuditableUserRepository repository) {
|
||||
Assert.notNull(repository);
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
Assert.notNull(repository);
|
||||
this.repository = repository;
|
||||
}
|
||||
public void setAuditor(AuditableUser auditor) {
|
||||
|
||||
this.auditor = auditor;
|
||||
}
|
||||
|
||||
public void setAuditor(AuditableUser auditor) {
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.domain.AuditorAware#getCurrentAuditor()
|
||||
*/
|
||||
public AuditableUser getCurrentAuditor() {
|
||||
|
||||
this.auditor = auditor;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.domain.AuditorAware#getCurrentAuditor()
|
||||
*/
|
||||
public AuditableUser getCurrentAuditor() {
|
||||
|
||||
return auditor;
|
||||
}
|
||||
return auditor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.jpa.domain.sample;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sample domain class representing roles. Mapped with XML.
|
||||
*
|
||||
@@ -24,62 +22,57 @@ package org.springframework.data.jpa.domain.sample;
|
||||
*/
|
||||
public class Role {
|
||||
|
||||
private static final long serialVersionUID = -8832631113344035104L;
|
||||
private static final String PREFIX = "ROLE_";
|
||||
private static final long serialVersionUID = -8832631113344035104L;
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* Creates a new instance of {@code Role}.
|
||||
*/
|
||||
public Role() {
|
||||
|
||||
/**
|
||||
* Creates a new instance of {@code Role}.
|
||||
*/
|
||||
public Role() {
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* Creates a new preconfigured {@code Role}.
|
||||
*
|
||||
* @param name
|
||||
*/
|
||||
public Role(final String name) {
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new preconfigured {@code Role}.
|
||||
*
|
||||
* @param name
|
||||
*/
|
||||
public Role(final String name) {
|
||||
/**
|
||||
* Returns the id.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Integer getId() {
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
/**
|
||||
* Returns the id.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Integer getId() {
|
||||
return PREFIX + name;
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
/**
|
||||
* Returns whether the role is to be considered new.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean isNew() {
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
return PREFIX + name;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether the role is to be considered new.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean isNew() {
|
||||
|
||||
return id == null;
|
||||
}
|
||||
return id == null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,48 +18,43 @@ package org.springframework.data.jpa.domain.sample;
|
||||
import javax.persistence.EmbeddedId;
|
||||
import javax.persistence.Entity;
|
||||
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@Entity
|
||||
public class SampleEntity {
|
||||
|
||||
@EmbeddedId
|
||||
protected SampleEntityPK id;
|
||||
@EmbeddedId
|
||||
protected SampleEntityPK id;
|
||||
|
||||
protected SampleEntity() {
|
||||
|
||||
protected SampleEntity() {
|
||||
}
|
||||
|
||||
}
|
||||
public SampleEntity(String first, String second) {
|
||||
|
||||
this.id = new SampleEntityPK(first, second);
|
||||
}
|
||||
|
||||
public SampleEntity(String first, String second) {
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
this.id = new SampleEntityPK(first, second);
|
||||
}
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
SampleEntity that = (SampleEntity) obj;
|
||||
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
return this.id.equals(that.id);
|
||||
}
|
||||
|
||||
if (!getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
SampleEntity that = (SampleEntity) obj;
|
||||
|
||||
return this.id.equals(that.id);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
return id.hashCode();
|
||||
}
|
||||
return id.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,67 +22,62 @@ import javax.persistence.Embeddable;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
@Embeddable
|
||||
public class SampleEntityPK implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 231060947L;
|
||||
private static final long serialVersionUID = 231060947L;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String first;
|
||||
@Column(nullable = false)
|
||||
private String second;
|
||||
@Column(nullable = false)
|
||||
private String first;
|
||||
@Column(nullable = false)
|
||||
private String second;
|
||||
|
||||
public SampleEntityPK() {
|
||||
|
||||
public SampleEntityPK() {
|
||||
this.first = null;
|
||||
this.second = null;
|
||||
}
|
||||
|
||||
this.first = null;
|
||||
this.second = null;
|
||||
}
|
||||
public SampleEntityPK(String first, String second) {
|
||||
|
||||
Assert.notNull(first);
|
||||
Assert.notNull(second);
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
public SampleEntityPK(String first, String second) {
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
Assert.notNull(first);
|
||||
Assert.notNull(second);
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!this.getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
SampleEntityPK that = (SampleEntityPK) obj;
|
||||
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
return this.first.equals(that.first) && this.second.equals(that.second);
|
||||
}
|
||||
|
||||
if (!this.getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
SampleEntityPK that = (SampleEntityPK) obj;
|
||||
|
||||
return this.first.equals(that.first) && this.second.equals(that.second);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
int result = 17;
|
||||
result += 31 * first.hashCode();
|
||||
result += 31 * second.hashCode();
|
||||
return result;
|
||||
}
|
||||
int result = 17;
|
||||
result += 31 * first.hashCode();
|
||||
result += 31 * second.hashCode();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package org.springframework.data.jpa.domain.sample;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
|
||||
@@ -28,11 +28,9 @@ import javax.persistence.ManyToMany;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.NamedQuery;
|
||||
|
||||
|
||||
/**
|
||||
* Domain class representing a person emphasizing the use of
|
||||
* {@code AbstractEntity}. No declaration of an id is required. The id is typed
|
||||
* by the parameterizable superclass.
|
||||
* Domain class representing a person emphasizing the use of {@code AbstractEntity}. No declaration of an id is
|
||||
* required. The id is typed by the parameterizable superclass.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@@ -40,260 +38,236 @@ import javax.persistence.NamedQuery;
|
||||
@NamedQuery(name = "User.findByEmailAddress", query = "SELECT u FROM User u WHERE u.emailAddress = ?1")
|
||||
public class User {
|
||||
|
||||
private static final long serialVersionUID = 8653688953355455933L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Integer id;
|
||||
private String firstname;
|
||||
private String lastname;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String emailAddress;
|
||||
|
||||
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
|
||||
private Set<User> colleagues;
|
||||
|
||||
@ManyToMany
|
||||
private Set<Role> roles;
|
||||
|
||||
@ManyToOne
|
||||
private User manager;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new empty instance of {@code User}.
|
||||
*/
|
||||
public User() {
|
||||
|
||||
this.roles = new HashSet<Role>();
|
||||
this.colleagues = new HashSet<User>();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new instance of {@code User} with preinitialized values for
|
||||
* firstname, lastname and email address.
|
||||
*
|
||||
* @param firstname
|
||||
* @param lastname
|
||||
* @param emailAddress
|
||||
*/
|
||||
public User(final String firstname, final String lastname,
|
||||
final String emailAddress) {
|
||||
|
||||
this();
|
||||
this.firstname = firstname;
|
||||
this.lastname = lastname;
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return the id
|
||||
*/
|
||||
public Integer getId() {
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param id the id to set
|
||||
*/
|
||||
public void setId(Integer id) {
|
||||
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the firstname.
|
||||
*
|
||||
* @return the firstname
|
||||
*/
|
||||
public String getFirstname() {
|
||||
|
||||
return firstname;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the firstname.
|
||||
*
|
||||
* @param firstname the firstname to set
|
||||
*/
|
||||
public void setFirstname(final String firstname) {
|
||||
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the lastname.
|
||||
*
|
||||
* @return the lastname
|
||||
*/
|
||||
public String getLastname() {
|
||||
|
||||
return lastname;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the lastname.
|
||||
*
|
||||
* @param lastname the lastname to set
|
||||
*/
|
||||
public void setLastname(String lastname) {
|
||||
|
||||
this.lastname = lastname;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the email address.
|
||||
*
|
||||
* @return the emailAddress
|
||||
*/
|
||||
public String getEmailAddress() {
|
||||
|
||||
return emailAddress;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the email address.
|
||||
*
|
||||
* @param emailAddress the emailAddress to set
|
||||
*/
|
||||
public void setEmailAddress(String emailAddress) {
|
||||
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the user's roles.
|
||||
*
|
||||
* @return the role
|
||||
*/
|
||||
public Set<Role> getRole() {
|
||||
|
||||
return roles;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gives the user a role. Adding a role the user already owns is a no-op.
|
||||
*/
|
||||
public void addRole(Role role) {
|
||||
|
||||
roles.add(role);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Revokes a role from a user.
|
||||
*
|
||||
* @param role
|
||||
*/
|
||||
public void removeRole(Role role) {
|
||||
|
||||
roles.remove(role);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the colleagues of the user.
|
||||
*
|
||||
* @return the colleagues
|
||||
*/
|
||||
public Set<User> getColleagues() {
|
||||
|
||||
return colleagues;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a new colleague to the user. Adding the user himself as colleague is
|
||||
* a no-op.
|
||||
*
|
||||
* @param collegue
|
||||
*/
|
||||
public void addColleague(User collegue) {
|
||||
|
||||
// Prevent from adding the user himself as colleague.
|
||||
if (this.equals(collegue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
colleagues.add(collegue);
|
||||
collegue.getColleagues().add(this);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes a colleague from the list of colleagues.
|
||||
*
|
||||
* @param colleague
|
||||
*/
|
||||
public void removeColleague(User colleague) {
|
||||
|
||||
colleagues.remove(colleague);
|
||||
colleague.getColleagues().remove(this);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return the manager
|
||||
*/
|
||||
public User getManager() {
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param manager the manager to set
|
||||
*/
|
||||
public void setManager(User manager) {
|
||||
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
if (!(obj instanceof User)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
User that = (User) obj;
|
||||
|
||||
if (null == this.getId() || null == that.getId()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.getId().equals(that.getId());
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
return "User: " + getId() + ", " + getFirstname() + " " + getLastname()
|
||||
+ ", " + getEmailAddress();
|
||||
}
|
||||
private static final long serialVersionUID = 8653688953355455933L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Integer id;
|
||||
private String firstname;
|
||||
private String lastname;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String emailAddress;
|
||||
|
||||
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
|
||||
private Set<User> colleagues;
|
||||
|
||||
@ManyToMany
|
||||
private Set<Role> roles;
|
||||
|
||||
@ManyToOne
|
||||
private User manager;
|
||||
|
||||
/**
|
||||
* Creates a new empty instance of {@code User}.
|
||||
*/
|
||||
public User() {
|
||||
|
||||
this.roles = new HashSet<Role>();
|
||||
this.colleagues = new HashSet<User>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of {@code User} with preinitialized values for firstname, lastname and email address.
|
||||
*
|
||||
* @param firstname
|
||||
* @param lastname
|
||||
* @param emailAddress
|
||||
*/
|
||||
public User(final String firstname, final String lastname, final String emailAddress) {
|
||||
|
||||
this();
|
||||
this.firstname = firstname;
|
||||
this.lastname = lastname;
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the id
|
||||
*/
|
||||
public Integer getId() {
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param id the id to set
|
||||
*/
|
||||
public void setId(Integer id) {
|
||||
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the firstname.
|
||||
*
|
||||
* @return the firstname
|
||||
*/
|
||||
public String getFirstname() {
|
||||
|
||||
return firstname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the firstname.
|
||||
*
|
||||
* @param firstname the firstname to set
|
||||
*/
|
||||
public void setFirstname(final String firstname) {
|
||||
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lastname.
|
||||
*
|
||||
* @return the lastname
|
||||
*/
|
||||
public String getLastname() {
|
||||
|
||||
return lastname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the lastname.
|
||||
*
|
||||
* @param lastname the lastname to set
|
||||
*/
|
||||
public void setLastname(String lastname) {
|
||||
|
||||
this.lastname = lastname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the email address.
|
||||
*
|
||||
* @return the emailAddress
|
||||
*/
|
||||
public String getEmailAddress() {
|
||||
|
||||
return emailAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the email address.
|
||||
*
|
||||
* @param emailAddress the emailAddress to set
|
||||
*/
|
||||
public void setEmailAddress(String emailAddress) {
|
||||
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user's roles.
|
||||
*
|
||||
* @return the role
|
||||
*/
|
||||
public Set<Role> getRole() {
|
||||
|
||||
return roles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the user a role. Adding a role the user already owns is a no-op.
|
||||
*/
|
||||
public void addRole(Role role) {
|
||||
|
||||
roles.add(role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revokes a role from a user.
|
||||
*
|
||||
* @param role
|
||||
*/
|
||||
public void removeRole(Role role) {
|
||||
|
||||
roles.remove(role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the colleagues of the user.
|
||||
*
|
||||
* @return the colleagues
|
||||
*/
|
||||
public Set<User> getColleagues() {
|
||||
|
||||
return colleagues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new colleague to the user. Adding the user himself as colleague is a no-op.
|
||||
*
|
||||
* @param collegue
|
||||
*/
|
||||
public void addColleague(User collegue) {
|
||||
|
||||
// Prevent from adding the user himself as colleague.
|
||||
if (this.equals(collegue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
colleagues.add(collegue);
|
||||
collegue.getColleagues().add(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a colleague from the list of colleagues.
|
||||
*
|
||||
* @param colleague
|
||||
*/
|
||||
public void removeColleague(User colleague) {
|
||||
|
||||
colleagues.remove(colleague);
|
||||
colleague.getColleagues().remove(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the manager
|
||||
*/
|
||||
public User getManager() {
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param manager the manager to set
|
||||
*/
|
||||
public void setManager(User manager) {
|
||||
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
if (!(obj instanceof User)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
User that = (User) obj;
|
||||
|
||||
if (null == this.getId() || null == that.getId()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.getId().equals(that.getId());
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
return "User: " + getId() + ", " + getFirstname() + " " + getLastname() + ", " + getEmailAddress();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import javax.persistence.criteria.Root;
|
||||
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
|
||||
/**
|
||||
* Collection of {@link Specification}s for a {@link User}.
|
||||
*
|
||||
@@ -30,61 +29,53 @@ import org.springframework.data.jpa.domain.Specification;
|
||||
*/
|
||||
public class UserSpecifications {
|
||||
|
||||
/**
|
||||
* A {@link Specification} to match on a {@link User}'s firstname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
public static Specification<User> userHasFirstname(final String firstname) {
|
||||
/**
|
||||
* A {@link Specification} to match on a {@link User}'s firstname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
public static Specification<User> userHasFirstname(final String firstname) {
|
||||
|
||||
return simplePropertySpec("firstname", firstname);
|
||||
}
|
||||
return simplePropertySpec("firstname", firstname);
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link Specification} to match on a {@link User}'s lastname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
public static Specification<User> userHasLastname(final String lastname) {
|
||||
|
||||
/**
|
||||
* A {@link Specification} to match on a {@link User}'s lastname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
public static Specification<User> userHasLastname(final String lastname) {
|
||||
return simplePropertySpec("lastname", lastname);
|
||||
}
|
||||
|
||||
return simplePropertySpec("lastname", lastname);
|
||||
}
|
||||
/**
|
||||
* A {@link Specification} to do a like-match on a {@link User}'s firstname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
public static Specification<User> userHasFirstnameLike(final String expression) {
|
||||
|
||||
return new Specification<User>() {
|
||||
|
||||
/**
|
||||
* A {@link Specification} to do a like-match on a {@link User}'s firstname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
public static Specification<User> userHasFirstnameLike(
|
||||
final String expression) {
|
||||
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
|
||||
|
||||
return new Specification<User>() {
|
||||
return cb.like(root.get("firstname").as(String.class), String.format("%%%s%%", expression));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Predicate toPredicate(Root<User> root,
|
||||
CriteriaQuery<?> query, CriteriaBuilder cb) {
|
||||
private static <T> Specification<T> simplePropertySpec(final String property, final Object value) {
|
||||
|
||||
return cb.like(root.get("firstname").as(String.class),
|
||||
String.format("%%%s%%", expression));
|
||||
}
|
||||
};
|
||||
}
|
||||
return new Specification<T>() {
|
||||
|
||||
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
|
||||
private static <T> Specification<T> simplePropertySpec(
|
||||
final String property, final Object value) {
|
||||
|
||||
return new Specification<T>() {
|
||||
|
||||
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
|
||||
CriteriaBuilder builder) {
|
||||
|
||||
return builder.equal(root.get(property), value);
|
||||
}
|
||||
};
|
||||
}
|
||||
return builder.equal(root.get(property), value);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link AuditingBeanFactoryPostProcessor}.
|
||||
*
|
||||
@@ -34,38 +33,30 @@ import org.springframework.core.io.ClassPathResource;
|
||||
*/
|
||||
public class AuditingBeanFactoryPostProcessorUnitTests {
|
||||
|
||||
ConfigurableListableBeanFactory beanFactory;
|
||||
AuditingBeanFactoryPostProcessor processor;
|
||||
ConfigurableListableBeanFactory beanFactory;
|
||||
AuditingBeanFactoryPostProcessor processor;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
beanFactory = new XmlBeanFactory(new ClassPathResource("auditing/" + getConfigFile()));
|
||||
|
||||
beanFactory =
|
||||
new XmlBeanFactory(new ClassPathResource("auditing/"
|
||||
+ getConfigFile()));
|
||||
processor = new AuditingBeanFactoryPostProcessor();
|
||||
}
|
||||
|
||||
processor = new AuditingBeanFactoryPostProcessor();
|
||||
}
|
||||
protected String getConfigFile() {
|
||||
|
||||
return "auditing-bfpp-context.xml";
|
||||
}
|
||||
|
||||
protected String getConfigFile() {
|
||||
@Test
|
||||
public void testname() throws Exception {
|
||||
|
||||
return "auditing-bfpp-context.xml";
|
||||
}
|
||||
processor.postProcessBeanFactory(beanFactory);
|
||||
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition("entityManagerFactory");
|
||||
|
||||
@Test
|
||||
public void testname() throws Exception {
|
||||
|
||||
processor.postProcessBeanFactory(beanFactory);
|
||||
|
||||
BeanDefinition definition =
|
||||
beanFactory.getBeanDefinition("entityManagerFactory");
|
||||
|
||||
assertTrue(Arrays
|
||||
.asList(definition.getDependsOn())
|
||||
.contains(
|
||||
AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME));
|
||||
}
|
||||
assertTrue(Arrays.asList(definition.getDependsOn()).contains(
|
||||
AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for {@link AuditingEntityListener}.
|
||||
*
|
||||
@@ -44,61 +43,55 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@DirtiesContext
|
||||
public class AuditingEntityListenerTests {
|
||||
|
||||
@Autowired
|
||||
AuditableUserRepository repository;
|
||||
@Autowired
|
||||
AuditableUserRepository repository;
|
||||
|
||||
@Autowired
|
||||
AuditorAwareStub auditorAware;
|
||||
@Autowired
|
||||
AuditorAwareStub auditorAware;
|
||||
|
||||
AuditableUser user;
|
||||
AuditableUser user;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
user = new AuditableUser();
|
||||
auditorAware.setAuditor(user);
|
||||
|
||||
user = new AuditableUser();
|
||||
auditorAware.setAuditor(user);
|
||||
repository.save(user);
|
||||
}
|
||||
|
||||
repository.save(user);
|
||||
}
|
||||
@Test
|
||||
public void auditsRootEntityCorrectly() throws Exception {
|
||||
|
||||
assertDatesSet(user);
|
||||
assertUserIsAuditor(user, user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void auditsRootEntityCorrectly() throws Exception {
|
||||
@Test
|
||||
public void auditsTransitiveEntitiesCorrectly() throws Exception {
|
||||
|
||||
assertDatesSet(user);
|
||||
assertUserIsAuditor(user, user);
|
||||
}
|
||||
AuditableRole role = new AuditableRole();
|
||||
role.setName("ADMIN");
|
||||
|
||||
user.addRole(role);
|
||||
repository.save(user);
|
||||
role = user.getRoles().iterator().next();
|
||||
|
||||
@Test
|
||||
public void auditsTransitiveEntitiesCorrectly() throws Exception {
|
||||
assertDatesSet(user);
|
||||
assertDatesSet(role);
|
||||
assertUserIsAuditor(user, user);
|
||||
assertUserIsAuditor(user, role);
|
||||
}
|
||||
|
||||
AuditableRole role = new AuditableRole();
|
||||
role.setName("ADMIN");
|
||||
private static void assertDatesSet(Auditable<?, ?> auditable) {
|
||||
|
||||
user.addRole(role);
|
||||
repository.save(user);
|
||||
role = user.getRoles().iterator().next();
|
||||
assertThat(auditable.getCreatedDate(), is(notNullValue()));
|
||||
assertThat(auditable.getLastModifiedDate(), is(notNullValue()));
|
||||
}
|
||||
|
||||
assertDatesSet(user);
|
||||
assertDatesSet(role);
|
||||
assertUserIsAuditor(user, user);
|
||||
assertUserIsAuditor(user, role);
|
||||
}
|
||||
private static void assertUserIsAuditor(AuditableUser user, Auditable<AuditableUser, ?> auditable) {
|
||||
|
||||
|
||||
private static void assertDatesSet(Auditable<?, ?> auditable) {
|
||||
|
||||
assertThat(auditable.getCreatedDate(), is(notNullValue()));
|
||||
assertThat(auditable.getLastModifiedDate(), is(notNullValue()));
|
||||
}
|
||||
|
||||
|
||||
private static void assertUserIsAuditor(AuditableUser user,
|
||||
Auditable<AuditableUser, ?> auditable) {
|
||||
|
||||
assertThat(auditable.getCreatedBy(), is(user));
|
||||
assertThat(auditable.getLastModifiedBy(), is(user));
|
||||
}
|
||||
assertThat(auditable.getCreatedBy(), is(user));
|
||||
assertThat(auditable.getLastModifiedBy(), is(user));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@ import org.junit.Test;
|
||||
import org.springframework.data.domain.AuditorAware;
|
||||
import org.springframework.data.jpa.domain.sample.AuditableUser;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@code AuditingEntityListener}.
|
||||
*
|
||||
@@ -32,119 +31,109 @@ import org.springframework.data.jpa.domain.sample.AuditableUser;
|
||||
@SuppressWarnings("unchecked")
|
||||
public class AuditingEntityListenerUnitTests {
|
||||
|
||||
AuditingEntityListener<AuditableUser> listener;
|
||||
AuditorAware<AuditableUser> auditorAware;
|
||||
AuditingEntityListener<AuditableUser> listener;
|
||||
AuditorAware<AuditableUser> auditorAware;
|
||||
|
||||
AuditableUser user;
|
||||
AuditableUser user;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
listener = new AuditingEntityListener<AuditableUser>();
|
||||
// Explicitly null the AuditorAware as it might have been DI'ed if test
|
||||
// is run in a test suite with integration tests
|
||||
// listener.setAuditorAware(null);
|
||||
|
||||
listener = new AuditingEntityListener<AuditableUser>();
|
||||
// Explicitly null the AuditorAware as it might have been DI'ed if test
|
||||
// is run in a test suite with integration tests
|
||||
// listener.setAuditorAware(null);
|
||||
user = new AuditableUser();
|
||||
|
||||
user = new AuditableUser();
|
||||
auditorAware = mock(AuditorAware.class);
|
||||
when(auditorAware.getCurrentAuditor()).thenReturn(user);
|
||||
}
|
||||
|
||||
auditorAware = mock(AuditorAware.class);
|
||||
when(auditorAware.getCurrentAuditor()).thenReturn(user);
|
||||
}
|
||||
/**
|
||||
* Checks that the advice does not set auditor on the target entity if no {@code AuditorAware} was configured.
|
||||
*/
|
||||
@Test
|
||||
public void doesNotSetAuditorIfNotConfigured() {
|
||||
|
||||
listener.touchForCreate(user);
|
||||
|
||||
/**
|
||||
* Checks that the advice does not set auditor on the target entity if no
|
||||
* {@code AuditorAware} was configured.
|
||||
*/
|
||||
@Test
|
||||
public void doesNotSetAuditorIfNotConfigured() {
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
listener.touchForCreate(user);
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getLastModifiedBy());
|
||||
}
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
/**
|
||||
* Checks that the advice sets the auditor on the target entity if an {@code AuditorAware} was configured.
|
||||
*/
|
||||
@Test
|
||||
public void setsAuditorIfConfigured() {
|
||||
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getLastModifiedBy());
|
||||
}
|
||||
listener.setAuditorAware(auditorAware);
|
||||
|
||||
listener.touchForCreate(user);
|
||||
|
||||
/**
|
||||
* Checks that the advice sets the auditor on the target entity if an
|
||||
* {@code AuditorAware} was configured.
|
||||
*/
|
||||
@Test
|
||||
public void setsAuditorIfConfigured() {
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
listener.setAuditorAware(auditorAware);
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
|
||||
listener.touchForCreate(user);
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
/**
|
||||
* Checks that the advice does not set modification information on creation if the falg is set to {@code false}.
|
||||
*/
|
||||
@Test
|
||||
public void honoursModifiedOnCreationFlag() {
|
||||
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
listener.setAuditorAware(auditorAware);
|
||||
listener.setModifyOnCreation(false);
|
||||
listener.touchForCreate(user);
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getCreatedBy());
|
||||
|
||||
assertNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
|
||||
/**
|
||||
* Checks that the advice does not set modification information on creation
|
||||
* if the falg is set to {@code false}.
|
||||
*/
|
||||
@Test
|
||||
public void honoursModifiedOnCreationFlag() {
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
listener.setAuditorAware(auditorAware);
|
||||
listener.setModifyOnCreation(false);
|
||||
listener.touchForCreate(user);
|
||||
/**
|
||||
* Tests that the advice only sets modification data if a not-new entity is handled.
|
||||
*/
|
||||
@Test
|
||||
public void onlySetsModificationDataOnNotNewEntities() {
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getCreatedBy());
|
||||
user = new AuditableUser(1L);
|
||||
|
||||
assertNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
listener.setAuditorAware(auditorAware);
|
||||
listener.touchForUpdate(user);
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
/**
|
||||
* Tests that the advice only sets modification data if a not-new entity is
|
||||
* handled.
|
||||
*/
|
||||
@Test
|
||||
public void onlySetsModificationDataOnNotNewEntities() {
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
user = new AuditableUser(1L);
|
||||
@Test
|
||||
public void doesNotSetTimeIfConfigured() throws Exception {
|
||||
|
||||
listener.setAuditorAware(auditorAware);
|
||||
listener.touchForUpdate(user);
|
||||
listener.setDateTimeForNow(false);
|
||||
listener.setAuditorAware(auditorAware);
|
||||
listener.touchForCreate(user);
|
||||
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void doesNotSetTimeIfConfigured() throws Exception {
|
||||
|
||||
listener.setDateTimeForNow(false);
|
||||
listener.setAuditorAware(auditorAware);
|
||||
listener.touchForCreate(user);
|
||||
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
}
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,36 +22,30 @@ import org.junit.Test;
|
||||
import org.springframework.beans.PropertyValue;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for the JPA {@code auditing} namespace element.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AuditingNamespaceUnitTests extends
|
||||
AuditingBeanFactoryPostProcessorUnitTests {
|
||||
public class AuditingNamespaceUnitTests extends AuditingBeanFactoryPostProcessorUnitTests {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.domain.support.
|
||||
* AuditingBeanFactoryPostProcessorUnitTests#getConfigFile()
|
||||
*/
|
||||
@Override
|
||||
protected String getConfigFile() {
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.domain.support.
|
||||
* AuditingBeanFactoryPostProcessorUnitTests#getConfigFile()
|
||||
*/
|
||||
@Override
|
||||
protected String getConfigFile() {
|
||||
|
||||
return "auditing-namespace-context.xml";
|
||||
}
|
||||
return "auditing-namespace-context.xml";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registersBeanDefinitions() throws Exception {
|
||||
|
||||
@Test
|
||||
public void registersBeanDefinitions() throws Exception {
|
||||
|
||||
BeanDefinition definition =
|
||||
beanFactory.getBeanDefinition(AuditingEntityListener.class
|
||||
.getName());
|
||||
PropertyValue propertyValue =
|
||||
definition.getPropertyValues().getPropertyValue("auditorAware");
|
||||
assertThat(propertyValue, is(notNullValue()));
|
||||
}
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition(AuditingEntityListener.class.getName());
|
||||
PropertyValue propertyValue = definition.getPropertyValues().getPropertyValue("auditorAware");
|
||||
assertThat(propertyValue, is(notNullValue()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,16 +19,13 @@ import org.springframework.data.jpa.repository.sample.UserRepository;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Testcase to run {@link UserRepository} integration tests on top of
|
||||
* EclipseLink.
|
||||
* Testcase to run {@link UserRepository} integration tests on top of EclipseLink.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@DirtiesContext
|
||||
@ContextConfiguration(value = "classpath:eclipselink.xml", inheritLocations = true)
|
||||
public class EclipseLinkNamespaceUserRepositoryTests extends
|
||||
NamespaceUserRepositoryTests {
|
||||
public class EclipseLinkNamespaceUserRepositoryTests extends NamespaceUserRepositoryTests {
|
||||
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import org.junit.Ignore;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Ignores some test cases using IN queries as long as we wait for fix for
|
||||
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477.
|
||||
@@ -29,6 +28,5 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
@Ignore
|
||||
@DirtiesContext
|
||||
@ContextConfiguration(value = "classpath:eclipselink.xml", inheritLocations = true)
|
||||
public class EclipseLinkUserRepositoryFinderTests extends
|
||||
UserRepositoryFinderTests {
|
||||
public class EclipseLinkUserRepositoryFinderTests extends UserRepositoryFinderTests {
|
||||
}
|
||||
|
||||
@@ -26,10 +26,8 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro
|
||||
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Use namespace context to run tests. Checks for existence of required
|
||||
* PostProcessors, too.
|
||||
* Use namespace context to run tests. Checks for existence of required PostProcessors, too.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @author Eberhard Wolff
|
||||
@@ -37,21 +35,19 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
@ContextConfiguration(locations = "classpath:config/namespace-application-context.xml", inheritLocations = false)
|
||||
public class NamespaceUserRepositoryTests extends UserRepositoryTests {
|
||||
|
||||
@Autowired
|
||||
ListableBeanFactory beanFactory;
|
||||
@Autowired
|
||||
ListableBeanFactory beanFactory;
|
||||
|
||||
@Test
|
||||
public void registersPostProcessors() {
|
||||
|
||||
@Test
|
||||
public void registersPostProcessors() {
|
||||
hasAtLeastOneBeanOfType(PersistenceAnnotationBeanPostProcessor.class);
|
||||
hasAtLeastOneBeanOfType(PersistenceExceptionTranslationPostProcessor.class);
|
||||
}
|
||||
|
||||
hasAtLeastOneBeanOfType(PersistenceAnnotationBeanPostProcessor.class);
|
||||
hasAtLeastOneBeanOfType(PersistenceExceptionTranslationPostProcessor.class);
|
||||
}
|
||||
private void hasAtLeastOneBeanOfType(Class<?> beanType) {
|
||||
|
||||
|
||||
private void hasAtLeastOneBeanOfType(Class<?> beanType) {
|
||||
|
||||
Map<String, ?> beans = beanFactory.getBeansOfType(beanType);
|
||||
assertFalse(beans.entrySet().isEmpty());
|
||||
}
|
||||
Map<String, ?> beans = beanFactory.getBeansOfType(beanType);
|
||||
assertFalse(beans.entrySet().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,10 +24,8 @@ import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
|
||||
/**
|
||||
* Simple test case launching an {@code ApplicationContext} to test
|
||||
* infrastructure configuration.
|
||||
* Simple test case launching an {@code ApplicationContext} to test infrastructure configuration.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@@ -35,18 +33,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
@ContextConfiguration(locations = "classpath:infrastructure.xml")
|
||||
public class ORMInfrastructureTests {
|
||||
|
||||
@Autowired
|
||||
ApplicationContext context;
|
||||
@Autowired
|
||||
ApplicationContext context;
|
||||
|
||||
/**
|
||||
* Tests, that the context got initialized and injected correctly.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void contextInitialized() throws Exception {
|
||||
|
||||
/**
|
||||
* Tests, that the context got initialized and injected correctly.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void contextInitialized() throws Exception {
|
||||
|
||||
assertNotNull(context);
|
||||
}
|
||||
assertNotNull(context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,14 +18,12 @@ package org.springframework.data.jpa.repository;
|
||||
import org.springframework.data.jpa.repository.sample.UserRepository;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Testcase to run {@link UserRepository} integration tests on top of OpenJPA.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@ContextConfiguration(value = "classpath:openjpa.xml", inheritLocations = true)
|
||||
public class OpenJpaNamespaceUserRepositoryTests extends
|
||||
NamespaceUserRepositoryTests {
|
||||
public class OpenJpaNamespaceUserRepositoryTests extends NamespaceUserRepositoryTests {
|
||||
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Integration tests for {@link RoleRepository}.
|
||||
*
|
||||
@@ -39,30 +38,28 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Transactional
|
||||
public class RoleRepositoryIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
RoleRepository repository;
|
||||
@Autowired
|
||||
RoleRepository repository;
|
||||
|
||||
@Test
|
||||
public void createsRole() throws Exception {
|
||||
|
||||
@Test
|
||||
public void createsRole() throws Exception {
|
||||
Role reference = new Role("ADMIN");
|
||||
Role result = repository.save(reference);
|
||||
assertThat(result, is(reference));
|
||||
}
|
||||
|
||||
Role reference = new Role("ADMIN");
|
||||
Role result = repository.save(reference);
|
||||
assertThat(result, is(reference));
|
||||
}
|
||||
@Test
|
||||
public void updatesRole() throws Exception {
|
||||
|
||||
Role reference = new Role("ADMIN");
|
||||
Role result = repository.save(reference);
|
||||
assertThat(result, is(reference));
|
||||
|
||||
@Test
|
||||
public void updatesRole() throws Exception {
|
||||
// Change role name
|
||||
ReflectionTestUtils.setField(reference, "name", "USER");
|
||||
repository.save(reference);
|
||||
|
||||
Role reference = new Role("ADMIN");
|
||||
Role result = repository.save(reference);
|
||||
assertThat(result, is(reference));
|
||||
|
||||
// Change role name
|
||||
ReflectionTestUtils.setField(reference, "name", "USER");
|
||||
repository.save(reference);
|
||||
|
||||
assertThat(repository.findOne(result.getId()), is(reference));
|
||||
}
|
||||
assertThat(repository.findOne(result.getId()), is(reference));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@@ -50,56 +49,52 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Transactional
|
||||
public class SimpleJpaParameterBindingTests {
|
||||
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void bindArray() {
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void bindArray() {
|
||||
User user = new User("Dave", "Matthews", "foo@bar.de");
|
||||
em.persist(user);
|
||||
em.flush();
|
||||
|
||||
User user = new User("Dave", "Matthews", "foo@bar.de");
|
||||
em.persist(user);
|
||||
em.flush();
|
||||
CriteriaBuilder builder = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaBuilder builder = em.getCriteriaBuilder();
|
||||
CriteriaQuery<User> criteria = builder.createQuery(User.class);
|
||||
Root<User> root = criteria.from(User.class);
|
||||
ParameterExpression<String[]> parameter = builder.parameter(String[].class);
|
||||
criteria.where(root.get("firstname").in(parameter));
|
||||
|
||||
CriteriaQuery<User> criteria = builder.createQuery(User.class);
|
||||
Root<User> root = criteria.from(User.class);
|
||||
ParameterExpression<String[]> parameter =
|
||||
builder.parameter(String[].class);
|
||||
criteria.where(root.get("firstname").in(parameter));
|
||||
TypedQuery<User> query = em.createQuery(criteria);
|
||||
query.setParameter(parameter, new String[] { "Dave", "Carter" });
|
||||
|
||||
TypedQuery<User> query = em.createQuery(criteria);
|
||||
query.setParameter(parameter, new String[] { "Dave", "Carter" });
|
||||
List<User> result = query.getResultList();
|
||||
assertThat(result.isEmpty(), is(false));
|
||||
}
|
||||
|
||||
List<User> result = query.getResultList();
|
||||
assertThat(result.isEmpty(), is(false));
|
||||
}
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void bindCollection() {
|
||||
|
||||
User user = new User("Dave", "Matthews", "foo@bar.de");
|
||||
em.persist(user);
|
||||
em.flush();
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void bindCollection() {
|
||||
CriteriaBuilder builder = em.getCriteriaBuilder();
|
||||
|
||||
User user = new User("Dave", "Matthews", "foo@bar.de");
|
||||
em.persist(user);
|
||||
em.flush();
|
||||
CriteriaQuery<User> criteria = builder.createQuery(User.class);
|
||||
Root<User> root = criteria.from(User.class);
|
||||
ParameterExpression<Collection> parameter = builder.parameter(Collection.class);
|
||||
criteria.where(root.get("firstname").in(parameter));
|
||||
|
||||
CriteriaBuilder builder = em.getCriteriaBuilder();
|
||||
TypedQuery<User> query = em.createQuery(criteria);
|
||||
|
||||
CriteriaQuery<User> criteria = builder.createQuery(User.class);
|
||||
Root<User> root = criteria.from(User.class);
|
||||
ParameterExpression<Collection> parameter =
|
||||
builder.parameter(Collection.class);
|
||||
criteria.where(root.get("firstname").in(parameter));
|
||||
query.setParameter(parameter, Arrays.asList("Dave"));
|
||||
|
||||
TypedQuery<User> query = em.createQuery(criteria);
|
||||
|
||||
query.setParameter(parameter, Arrays.asList("Dave"));
|
||||
|
||||
List<User> result = query.getResultList();
|
||||
assertThat(result.isEmpty(), is(false));
|
||||
assertThat(result.get(0), is(user));
|
||||
}
|
||||
List<User> result = query.getResultList();
|
||||
assertThat(result.isEmpty(), is(false));
|
||||
assertThat(result.get(0), is(user));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,10 +36,8 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for executing finders, thus testing various query lookup
|
||||
* strategies.
|
||||
* Integration test for executing finders, thus testing various query lookup strategies.
|
||||
*
|
||||
* @see QueryLookupStrategy
|
||||
* @author Oliver Gierke
|
||||
@@ -49,145 +47,128 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Transactional
|
||||
public class UserRepositoryFinderTests {
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
User dave, carter, oliver;
|
||||
User dave, carter, oliver;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
// This one matches both criterias
|
||||
dave = new User("Dave", "Matthews", "dave@dmband.com");
|
||||
userRepository.save(dave);
|
||||
|
||||
// This one matches both criterias
|
||||
dave = new User("Dave", "Matthews", "dave@dmband.com");
|
||||
userRepository.save(dave);
|
||||
// This one matches only the second one
|
||||
carter = new User("Carter", "Beauford", "carter@dmband.com");
|
||||
userRepository.save(carter);
|
||||
|
||||
// This one matches only the second one
|
||||
carter = new User("Carter", "Beauford", "carter@dmband.com");
|
||||
userRepository.save(carter);
|
||||
oliver = new User("Oliver August", "Matthews", "oliver@dmband.com");
|
||||
userRepository.save(oliver);
|
||||
}
|
||||
|
||||
oliver = new User("Oliver August", "Matthews", "oliver@dmband.com");
|
||||
userRepository.save(oliver);
|
||||
}
|
||||
/**
|
||||
* Tests creation of a simple query.
|
||||
*/
|
||||
@Test
|
||||
public void testSimpleCustomCreatedFinder() {
|
||||
|
||||
User user = userRepository.findByEmailAddressAndLastname("dave@dmband.com", "Matthews");
|
||||
assertEquals(dave, user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests creation of a simple query.
|
||||
*/
|
||||
@Test
|
||||
public void testSimpleCustomCreatedFinder() {
|
||||
/**
|
||||
* Tests that the repository returns {@code null} for not found objects for finder methods that return a single domain
|
||||
* object.
|
||||
*/
|
||||
@Test
|
||||
public void returnsNullIfNothingFound() {
|
||||
|
||||
User user =
|
||||
userRepository.findByEmailAddressAndLastname("dave@dmband.com",
|
||||
"Matthews");
|
||||
assertEquals(dave, user);
|
||||
}
|
||||
User user = userRepository.findByEmailAddress("foobar");
|
||||
assertEquals(null, user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests creation of a simple query consisting of {@code AND} and {@code OR} parts.
|
||||
*/
|
||||
@Test
|
||||
public void testAndOrFinder() {
|
||||
|
||||
/**
|
||||
* Tests that the repository returns {@code null} for not found objects for
|
||||
* finder methods that return a single domain object.
|
||||
*/
|
||||
@Test
|
||||
public void returnsNullIfNothingFound() {
|
||||
List<User> users = userRepository.findByEmailAddressAndLastnameOrFirstname("dave@dmband.com", "Matthews", "Carter");
|
||||
|
||||
User user = userRepository.findByEmailAddress("foobar");
|
||||
assertEquals(null, user);
|
||||
}
|
||||
assertNotNull(users);
|
||||
assertEquals(2, users.size());
|
||||
assertTrue(users.contains(dave));
|
||||
assertTrue(users.contains(carter));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executesPagingMethodToPageCorrectly() {
|
||||
|
||||
/**
|
||||
* Tests creation of a simple query consisting of {@code AND} and {@code OR}
|
||||
* parts.
|
||||
*/
|
||||
@Test
|
||||
public void testAndOrFinder() {
|
||||
Page<User> page = userRepository.findByLastname(new PageRequest(0, 1), "Matthews");
|
||||
assertThat(page.getNumberOfElements(), is(1));
|
||||
assertThat(page.getTotalElements(), is(2L));
|
||||
assertThat(page.getTotalPages(), is(2));
|
||||
}
|
||||
|
||||
List<User> users =
|
||||
userRepository.findByEmailAddressAndLastnameOrFirstname(
|
||||
"dave@dmband.com", "Matthews", "Carter");
|
||||
@Test
|
||||
public void executesPagingMethodToListCorrectly() {
|
||||
|
||||
assertNotNull(users);
|
||||
assertEquals(2, users.size());
|
||||
assertTrue(users.contains(dave));
|
||||
assertTrue(users.contains(carter));
|
||||
}
|
||||
List<User> list = userRepository.findByFirstname("Carter", new PageRequest(0, 1));
|
||||
assertThat(list.size(), is(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executesInKeywordForPageCorrectly() {
|
||||
|
||||
@Test
|
||||
public void executesPagingMethodToPageCorrectly() {
|
||||
Page<User> page = userRepository.findByFirstnameIn(new PageRequest(0, 1), "Dave", "Oliver August");
|
||||
|
||||
Page<User> page =
|
||||
userRepository
|
||||
.findByLastname(new PageRequest(0, 1), "Matthews");
|
||||
assertThat(page.getNumberOfElements(), is(1));
|
||||
assertThat(page.getTotalElements(), is(2L));
|
||||
assertThat(page.getTotalPages(), is(2));
|
||||
}
|
||||
assertThat(page.getNumberOfElements(), is(1));
|
||||
assertThat(page.getTotalElements(), is(2L));
|
||||
assertThat(page.getTotalPages(), is(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executesNotInQueryCorrectly() throws Exception {
|
||||
|
||||
@Test
|
||||
public void executesPagingMethodToListCorrectly() {
|
||||
List<User> result = userRepository.findByFirstnameNotIn(Arrays.asList("Dave", "Carter"));
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(oliver));
|
||||
}
|
||||
|
||||
List<User> list =
|
||||
userRepository.findByFirstname("Carter", new PageRequest(0, 1));
|
||||
assertThat(list.size(), is(1));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void executesInKeywordForPageCorrectly() {
|
||||
|
||||
Page<User> page =
|
||||
userRepository.findByFirstnameIn(new PageRequest(0, 1), "Dave",
|
||||
"Oliver August");
|
||||
|
||||
assertThat(page.getNumberOfElements(), is(1));
|
||||
assertThat(page.getTotalElements(), is(2L));
|
||||
assertThat(page.getTotalPages(), is(2));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void executesNotInQueryCorrectly() throws Exception {
|
||||
|
||||
List<User> result =
|
||||
userRepository.findByFirstnameNotIn(Arrays.asList("Dave",
|
||||
"Carter"));
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(oliver));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
public void findsByLastnameIgnoringCase() throws Exception {
|
||||
List<User> result = userRepository.findByLastnameIgnoringCase("BeAUfoRd");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findsByLastnameIgnoringCaseLike() throws Exception {
|
||||
List<User> result = userRepository.findByLastnameIgnoringCaseLike("BeAUfo%");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findByLastnameAndFirstnameAllIgnoringCase() throws Exception {
|
||||
List<User> result = userRepository.findByLastnameAndFirstnameAllIgnoringCase("MaTTheWs","DaVe");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(dave));
|
||||
List<User> result = userRepository.findByLastnameIgnoringCase("BeAUfoRd");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
public void findsByLastnameIgnoringCaseLike() throws Exception {
|
||||
List<User> result = userRepository.findByLastnameIgnoringCaseLike("BeAUfo%");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findByLastnameAndFirstnameAllIgnoringCase() throws Exception {
|
||||
List<User> result = userRepository.findByLastnameAndFirstnameAllIgnoringCase("MaTTheWs", "DaVe");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(dave));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void respectsPageableOrderOnQueryGenerateFromMethodName() throws Exception {
|
||||
Page<User> ascending = userRepository.findByLastnameIgnoringCase(new PageRequest(0, 10, new Sort(Direction.ASC, "firstname")),"Matthews");
|
||||
Page<User> descending = userRepository.findByLastnameIgnoringCase(new PageRequest(0, 10, new Sort(Direction.DESC, "firstname")),"Matthews");
|
||||
Page<User> ascending = userRepository.findByLastnameIgnoringCase(new PageRequest(0, 10, new Sort(Direction.ASC,
|
||||
"firstname")), "Matthews");
|
||||
Page<User> descending = userRepository.findByLastnameIgnoringCase(new PageRequest(0, 10, new Sort(Direction.DESC,
|
||||
"firstname")), "Matthews");
|
||||
assertThat(ascending.getTotalElements(), is(2L));
|
||||
assertThat(descending.getTotalElements(), is(2L));
|
||||
assertThat(ascending.getContent().get(0).getFirstname(), is(not(equalTo(descending.getContent().get(0).getFirstname()))));
|
||||
assertThat(ascending.getContent().get(0).getFirstname(), is(not(equalTo(descending.getContent().get(0)
|
||||
.getFirstname()))));
|
||||
assertThat(ascending.getContent().get(0).getFirstname(), is(equalTo(descending.getContent().get(1).getFirstname())));
|
||||
assertThat(ascending.getContent().get(1).getFirstname(), is(equalTo(descending.getContent().get(0).getFirstname())));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,7 +25,6 @@ import org.springframework.data.jpa.repository.sample.RoleRepository;
|
||||
import org.springframework.data.jpa.repository.sample.UserRepository;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
|
||||
/**
|
||||
* Abstract base class for integration test for namespace configuration.
|
||||
*
|
||||
@@ -34,24 +33,23 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
public abstract class AbstractRepositoryConfigTests {
|
||||
|
||||
@Autowired(required = false)
|
||||
UserRepository userRepository;
|
||||
@Autowired(required = false)
|
||||
UserRepository userRepository;
|
||||
|
||||
@Autowired(required = false)
|
||||
RoleRepository roleRepository;
|
||||
@Autowired(required = false)
|
||||
RoleRepository roleRepository;
|
||||
|
||||
@Autowired(required = false)
|
||||
AuditableUserRepository auditableUserRepository;
|
||||
@Autowired(required = false)
|
||||
AuditableUserRepository auditableUserRepository;
|
||||
|
||||
/**
|
||||
* Asserts that context creation detects 3 repository beans.
|
||||
*/
|
||||
@Test
|
||||
public void testContextCreation() {
|
||||
|
||||
/**
|
||||
* Asserts that context creation detects 3 repository beans.
|
||||
*/
|
||||
@Test
|
||||
public void testContextCreation() {
|
||||
|
||||
assertNotNull(userRepository);
|
||||
assertNotNull(roleRepository);
|
||||
assertNotNull(auditableUserRepository);
|
||||
}
|
||||
assertNotNull(userRepository);
|
||||
assertNotNull(roleRepository);
|
||||
assertNotNull(auditableUserRepository);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
|
||||
/**
|
||||
* Integration tests for {@link AuditingBeanDefinitionParser}.
|
||||
*
|
||||
@@ -32,31 +31,25 @@ import org.springframework.core.io.ClassPathResource;
|
||||
*/
|
||||
public class AuditingBeanDefinitionParserTests {
|
||||
|
||||
@Test
|
||||
public void settingDatesIsConfigured() throws Exception {
|
||||
@Test
|
||||
public void settingDatesIsConfigured() throws Exception {
|
||||
|
||||
assertSetDatesIsSetTo("auditing/auditing-namespace-context.xml", "true");
|
||||
}
|
||||
assertSetDatesIsSetTo("auditing/auditing-namespace-context.xml", "true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notSettingDatesIsConfigured() throws Exception {
|
||||
|
||||
@Test
|
||||
public void notSettingDatesIsConfigured() throws Exception {
|
||||
assertSetDatesIsSetTo("auditing/auditing-namespace-context2.xml", "false");
|
||||
}
|
||||
|
||||
assertSetDatesIsSetTo("auditing/auditing-namespace-context2.xml",
|
||||
"false");
|
||||
}
|
||||
private void assertSetDatesIsSetTo(String configFile, String value) {
|
||||
|
||||
|
||||
private void assertSetDatesIsSetTo(String configFile, String value) {
|
||||
|
||||
XmlBeanFactory factory =
|
||||
new XmlBeanFactory(new ClassPathResource(configFile));
|
||||
BeanDefinition definition =
|
||||
factory.getBeanDefinition(AuditingBeanDefinitionParser.AUDITING_ENTITY_LISTENER_CLASS_NAME);
|
||||
PropertyValue propertyValue =
|
||||
definition.getPropertyValues().getPropertyValue(
|
||||
"dateTimeForNow");
|
||||
assertThat(propertyValue, is(notNullValue()));
|
||||
assertThat((String) propertyValue.getValue(), is(value));
|
||||
}
|
||||
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(configFile));
|
||||
BeanDefinition definition = factory
|
||||
.getBeanDefinition(AuditingBeanDefinitionParser.AUDITING_ENTITY_LISTENER_CLASS_NAME);
|
||||
PropertyValue propertyValue = definition.getPropertyValues().getPropertyValue("dateTimeForNow");
|
||||
assertThat(propertyValue, is(notNullValue()));
|
||||
assertThat((String) propertyValue.getValue(), is(value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,16 +28,14 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* Annotation to exclude repository interfaces from being picked up and thus in
|
||||
* consequence getting an instance being created.
|
||||
* Annotation to exclude repository interfaces from being picked up and thus in consequence getting an instance being
|
||||
* created.
|
||||
* <p>
|
||||
* This will typically be used when providing an extended base interface for all
|
||||
* repositories in combination with a custom repository base class to implement
|
||||
* methods declared in that intermediate interface. In this case you typically
|
||||
* derive your concrete repository interfaces from the intermediate one but
|
||||
* don't want to create a Spring bean for the intermediate interface.
|
||||
* This will typically be used when providing an extended base interface for all repositories in combination with a
|
||||
* custom repository base class to implement methods declared in that intermediate interface. In this case you typically
|
||||
* derive your concrete repository interfaces from the intermediate one but don't want to create a Spring bean for the
|
||||
* intermediate interface.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@@ -45,44 +43,40 @@ import org.springframework.util.Assert;
|
||||
@ContextConfiguration(locations = "classpath:config/namespace-customfactory-context.xml")
|
||||
public class CustomRepositoryFactoryConfigTests {
|
||||
|
||||
@Autowired(required = false)
|
||||
UserCustomExtendedRepository userRepository;
|
||||
@Autowired(required = false)
|
||||
UserCustomExtendedRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
DelegatingTransactionManager transactionManager;
|
||||
@Autowired
|
||||
DelegatingTransactionManager transactionManager;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
transactionManager.resetCount();
|
||||
}
|
||||
|
||||
transactionManager.resetCount();
|
||||
}
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testCustomFactoryUsed() {
|
||||
|
||||
Assert.notNull(userRepository);
|
||||
userRepository.customMethod(1);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testCustomFactoryUsed() {
|
||||
@Test
|
||||
public void reconfiguresTransactionalMethodWithoutGenericParameter() {
|
||||
|
||||
Assert.notNull(userRepository);
|
||||
userRepository.customMethod(1);
|
||||
}
|
||||
userRepository.findAll();
|
||||
|
||||
assertFalse(transactionManager.getDefinition().isReadOnly());
|
||||
assertThat(transactionManager.getDefinition().getTimeout(), is(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reconfiguresTransactionalMethodWithoutGenericParameter() {
|
||||
@Test
|
||||
public void reconfiguresTransactionalMethodWithGenericParameter() {
|
||||
|
||||
userRepository.findAll();
|
||||
userRepository.findOne(1);
|
||||
|
||||
assertFalse(transactionManager.getDefinition().isReadOnly());
|
||||
assertThat(transactionManager.getDefinition().getTimeout(), is(10));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void reconfiguresTransactionalMethodWithGenericParameter() {
|
||||
|
||||
userRepository.findOne(1);
|
||||
|
||||
assertFalse(transactionManager.getDefinition().isReadOnly());
|
||||
assertThat(transactionManager.getDefinition().getTimeout(), is(10));
|
||||
}
|
||||
assertFalse(transactionManager.getDefinition().isReadOnly());
|
||||
assertThat(transactionManager.getDefinition().getTimeout(), is(10));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for {@link JpaRepositoryConfigDefinitionParser}.
|
||||
*
|
||||
@@ -32,22 +31,17 @@ import org.springframework.core.io.ClassPathResource;
|
||||
*/
|
||||
public class JpaRepositoryConfigDefinitionParserTests {
|
||||
|
||||
@Test
|
||||
public void getsTransactionManagerSet() throws Exception {
|
||||
@Test
|
||||
public void getsTransactionManagerSet() throws Exception {
|
||||
|
||||
XmlBeanFactory factory =
|
||||
new XmlBeanFactory(new ClassPathResource(
|
||||
"multiple-entity-manager-integration-context.xml"));
|
||||
XmlBeanFactory factory = new XmlBeanFactory(
|
||||
new ClassPathResource("multiple-entity-manager-integration-context.xml"));
|
||||
|
||||
BeanDefinition definition =
|
||||
factory.getBeanDefinition("auditableUserRepository");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
BeanDefinition definition = factory.getBeanDefinition("auditableUserRepository");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
|
||||
PropertyValue transactionManager =
|
||||
definition.getPropertyValues().getPropertyValue(
|
||||
"transactionManager");
|
||||
assertThat(transactionManager, is(notNullValue()));
|
||||
assertThat(transactionManager.getValue().toString(),
|
||||
is("transactionManager-2"));
|
||||
}
|
||||
PropertyValue transactionManager = definition.getPropertyValues().getPropertyValue("transactionManager");
|
||||
assertThat(transactionManager, is(notNullValue()));
|
||||
assertThat(transactionManager.getValue().toString(), is("transactionManager-2"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import org.springframework.data.repository.query.QueryLookupStrategy.Key;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for XML configuration of {@link QueryLookupStrategy.Key}s.
|
||||
*
|
||||
@@ -38,22 +37,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
@ContextConfiguration(locations = "classpath:config/lookup-strategies-context.xml")
|
||||
public class QueryLookupStrategyTests {
|
||||
|
||||
@Autowired
|
||||
ApplicationContext context;
|
||||
@Autowired
|
||||
ApplicationContext context;
|
||||
|
||||
/**
|
||||
* Assert that {@link QueryLookupStrategy#USE_DECLARED_QUERY} is being set on the factory if configured.
|
||||
*/
|
||||
@Test
|
||||
public void assertUseDeclaredQuery() {
|
||||
|
||||
/**
|
||||
* Assert that {@link QueryLookupStrategy#USE_DECLARED_QUERY} is being set
|
||||
* on the factory if configured.
|
||||
*/
|
||||
@Test
|
||||
public void assertUseDeclaredQuery() {
|
||||
JpaRepositoryFactoryBean<?, ?, ?> factory = context.getBean("&roleRepository", JpaRepositoryFactoryBean.class);
|
||||
|
||||
JpaRepositoryFactoryBean<?, ?, ?> factory =
|
||||
context.getBean("&roleRepository",
|
||||
JpaRepositoryFactoryBean.class);
|
||||
|
||||
assertEquals(Key.USE_DECLARED_QUERY,
|
||||
getField(factory, "queryLookupStrategyKey"));
|
||||
}
|
||||
assertEquals(Key.USE_DECLARED_QUERY, getField(factory, "queryLookupStrategyKey"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ package org.springframework.data.jpa.repository.config;
|
||||
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test to test repository auto configuration.
|
||||
*
|
||||
|
||||
@@ -17,7 +17,6 @@ package org.springframework.data.jpa.repository.config;
|
||||
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for repository namespace configuration.
|
||||
*
|
||||
|
||||
@@ -19,29 +19,26 @@ import static org.junit.Assert.*;
|
||||
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test to test
|
||||
* {@link org.springframework.core.type.filter.TypeFilter} integration into
|
||||
* namespace.
|
||||
* Integration test to test {@link org.springframework.core.type.filter.TypeFilter} integration into namespace.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@ContextConfiguration(locations = "classpath:config/namespace-autoconfig-typefilter-context.xml")
|
||||
public class TypeFilterConfigTest extends AbstractRepositoryConfigTests {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.config.AbstractRepositoryConfigTests
|
||||
* #testContextCreation()
|
||||
*/
|
||||
@Override
|
||||
public void testContextCreation() {
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.config.AbstractRepositoryConfigTests
|
||||
* #testContextCreation()
|
||||
*/
|
||||
@Override
|
||||
public void testContextCreation() {
|
||||
|
||||
assertNotNull(userRepository);
|
||||
assertNotNull(roleRepository);
|
||||
assertNull(auditableUserRepository);
|
||||
}
|
||||
assertNotNull(userRepository);
|
||||
assertNotNull(roleRepository);
|
||||
assertNull(auditableUserRepository);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,37 +22,32 @@ import javax.persistence.EntityManager;
|
||||
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
|
||||
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
|
||||
|
||||
|
||||
/**
|
||||
* Sample custom repository base class implementing common custom functionality
|
||||
* for all derived repository instances.
|
||||
* Sample custom repository base class implementing common custom functionality for all derived repository instances.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class CustomGenericJpaRepository<T, ID extends Serializable> extends
|
||||
SimpleJpaRepository<T, ID> implements CustomGenericRepository<T, ID> {
|
||||
public class CustomGenericJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements
|
||||
CustomGenericRepository<T, ID> {
|
||||
|
||||
/**
|
||||
* @param domainClass
|
||||
* @param entityManager
|
||||
*/
|
||||
public CustomGenericJpaRepository(JpaEntityInformation<T, ID> metadata,
|
||||
EntityManager entityManager) {
|
||||
/**
|
||||
* @param domainClass
|
||||
* @param entityManager
|
||||
*/
|
||||
public CustomGenericJpaRepository(JpaEntityInformation<T, ID> metadata, EntityManager entityManager) {
|
||||
|
||||
super(metadata, entityManager);
|
||||
}
|
||||
super(metadata, entityManager);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.custom.CustomGenericRepository
|
||||
* #customMethod(java.io.Serializable)
|
||||
*/
|
||||
public T customMethod(ID id) {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.custom.CustomGenericRepository
|
||||
* #customMethod(java.io.Serializable)
|
||||
*/
|
||||
public T customMethod(ID id) {
|
||||
|
||||
throw new UnsupportedOperationException(
|
||||
"Forced exception for testing purposes.");
|
||||
}
|
||||
throw new UnsupportedOperationException("Forced exception for testing purposes.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,55 +26,47 @@ import org.springframework.data.jpa.repository.support.JpaEntityInformation;
|
||||
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
|
||||
|
||||
/**
|
||||
* Sample implementation of a custom {@link JpaRepositoryFactory} to use a
|
||||
* custom repository base class.
|
||||
* Sample implementation of a custom {@link JpaRepositoryFactory} to use a custom repository base class.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class CustomGenericJpaRepositoryFactory extends JpaRepositoryFactory {
|
||||
|
||||
/**
|
||||
* @param entityManager
|
||||
*/
|
||||
public CustomGenericJpaRepositoryFactory(EntityManager entityManager) {
|
||||
/**
|
||||
* @param entityManager
|
||||
*/
|
||||
public CustomGenericJpaRepositoryFactory(EntityManager entityManager) {
|
||||
|
||||
super(entityManager);
|
||||
}
|
||||
super(entityManager);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.support.GenericJpaRepositoryFactory
|
||||
* #getTargetRepository(java.lang.Class, javax.persistence.EntityManager)
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected JpaRepository<?, ?> getTargetRepository(RepositoryMetadata metadata, EntityManager em) {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.support.GenericJpaRepositoryFactory
|
||||
* #getTargetRepository(java.lang.Class, javax.persistence.EntityManager)
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected JpaRepository<?, ?> getTargetRepository(
|
||||
RepositoryMetadata metadata, EntityManager em) {
|
||||
JpaEntityInformation<Object, Serializable> entityMetadata = mock(JpaEntityInformation.class);
|
||||
when(entityMetadata.getJavaType()).thenReturn((Class<Object>) metadata.getDomainClass());
|
||||
return new CustomGenericJpaRepository<Object, Serializable>(entityMetadata, em);
|
||||
}
|
||||
|
||||
JpaEntityInformation<Object, Serializable> entityMetadata =
|
||||
mock(JpaEntityInformation.class);
|
||||
when(entityMetadata.getJavaType()).thenReturn(
|
||||
(Class<Object>) metadata.getDomainClass());
|
||||
return new CustomGenericJpaRepository<Object, Serializable>(
|
||||
entityMetadata, em);
|
||||
}
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.support.RepositoryFactorySupport#
|
||||
* getRepositoryBaseClass()
|
||||
*/
|
||||
@Override
|
||||
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.support.RepositoryFactorySupport#
|
||||
* getRepositoryBaseClass()
|
||||
*/
|
||||
@Override
|
||||
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
|
||||
|
||||
return CustomGenericJpaRepository.class;
|
||||
}
|
||||
return CustomGenericJpaRepository.class;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,25 +23,24 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
|
||||
|
||||
|
||||
/**
|
||||
* {@link JpaRepositoryFactoryBean} to return a custom repository base class.
|
||||
*
|
||||
* @author Gil Markham
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class CustomGenericJpaRepositoryFactoryBean<T extends JpaRepository<Object, Serializable>>
|
||||
extends JpaRepositoryFactoryBean<T, Object, Serializable> {
|
||||
public class CustomGenericJpaRepositoryFactoryBean<T extends JpaRepository<Object, Serializable>> extends
|
||||
JpaRepositoryFactoryBean<T, Object, Serializable> {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.repository.support.
|
||||
* GenericJpaRepositoryFactoryBean#getFactory()
|
||||
*/
|
||||
@Override
|
||||
protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.repository.support.
|
||||
* GenericJpaRepositoryFactoryBean#getFactory()
|
||||
*/
|
||||
@Override
|
||||
protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
|
||||
|
||||
return new CustomGenericJpaRepositoryFactory(em);
|
||||
}
|
||||
return new CustomGenericJpaRepositoryFactory(em);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,24 +21,21 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.repository.NoRepositoryBean;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
|
||||
/**
|
||||
* Extension of {@link CrudRepository} to be added on a custom repository base
|
||||
* class. This tests the facility to implement custom base class functionality
|
||||
* for all repository instances derived from this interface and implementation
|
||||
* Extension of {@link CrudRepository} to be added on a custom repository base class. This tests the facility to
|
||||
* implement custom base class functionality for all repository instances derived from this interface and implementation
|
||||
* base class.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@NoRepositoryBean
|
||||
public interface CustomGenericRepository<T, ID extends Serializable> extends
|
||||
JpaRepository<T, ID> {
|
||||
public interface CustomGenericRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
|
||||
|
||||
/**
|
||||
* Custom sample method.
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
T customMethod(ID id);
|
||||
/**
|
||||
* Custom sample method.
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
T customMethod(ID id);
|
||||
}
|
||||
|
||||
@@ -20,28 +20,24 @@ import java.util.List;
|
||||
import org.springframework.data.jpa.domain.sample.User;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Custom Extended repository interface for a {@code User}. This relies on the
|
||||
* custom intermediate repository interface {@link CustomGenericRepository}.
|
||||
* Custom Extended repository interface for a {@code User}. This relies on the custom intermediate repository interface
|
||||
* {@link CustomGenericRepository}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface UserCustomExtendedRepository extends
|
||||
CustomGenericRepository<User, Integer> {
|
||||
public interface UserCustomExtendedRepository extends CustomGenericRepository<User, Integer> {
|
||||
|
||||
/**
|
||||
* Sample method to test reconfiguring transactions on CRUD methods in
|
||||
* combination with custom factory.
|
||||
*
|
||||
* @see #421
|
||||
*/
|
||||
/**
|
||||
* Sample method to test reconfiguring transactions on CRUD methods in combination with custom factory.
|
||||
*
|
||||
* @see #421
|
||||
*/
|
||||
|
||||
@Transactional(readOnly = false, timeout = 10)
|
||||
List<User> findAll();
|
||||
@Transactional(readOnly = false, timeout = 10)
|
||||
List<User> findAll();
|
||||
|
||||
|
||||
@Transactional(readOnly = false, timeout = 10)
|
||||
User findOne(Integer id);
|
||||
@Transactional(readOnly = false, timeout = 10)
|
||||
User findOne(Integer id);
|
||||
|
||||
}
|
||||
@@ -29,7 +29,6 @@ import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.jpa.repository.query.JpaQueryExecution.ModifyingExecution;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link QueryExecution}.
|
||||
*
|
||||
@@ -38,88 +37,79 @@ import org.springframework.data.jpa.repository.query.JpaQueryExecution.Modifying
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JpaQueryExecutionUnitTests {
|
||||
|
||||
@Mock
|
||||
EntityManager em;
|
||||
@Mock
|
||||
AbstractStringBasedJpaQuery jpaQuery;
|
||||
@Mock
|
||||
Query query;
|
||||
@Mock
|
||||
JpaQueryMethod method;
|
||||
@Mock
|
||||
EntityManager em;
|
||||
@Mock
|
||||
AbstractStringBasedJpaQuery jpaQuery;
|
||||
@Mock
|
||||
Query query;
|
||||
@Mock
|
||||
JpaQueryMethod method;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullQuery() {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullQuery() {
|
||||
new StubQueryExecution().execute(null, new Object[] {});
|
||||
}
|
||||
|
||||
new StubQueryExecution().execute(null, new Object[] {});
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullBinder() throws Exception {
|
||||
|
||||
new StubQueryExecution().execute(jpaQuery, null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullBinder() throws Exception {
|
||||
@Test
|
||||
public void transformsNoResultExceptionToNull() {
|
||||
|
||||
new StubQueryExecution().execute(jpaQuery, null);
|
||||
}
|
||||
assertThat(new JpaQueryExecution() {
|
||||
|
||||
@Override
|
||||
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
|
||||
|
||||
@Test
|
||||
public void transformsNoResultExceptionToNull() {
|
||||
return null;
|
||||
}
|
||||
}.execute(jpaQuery, new Object[] {}), is(nullValue()));
|
||||
}
|
||||
|
||||
assertThat(new JpaQueryExecution() {
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void modifyingExecutionClearsEntityManagerIfSet() {
|
||||
|
||||
@Override
|
||||
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
|
||||
when(query.executeUpdate()).thenReturn(0);
|
||||
when(method.getReturnType()).thenReturn((Class) void.class);
|
||||
when(jpaQuery.createQuery(Mockito.any(Object[].class))).thenReturn(query);
|
||||
|
||||
return null;
|
||||
}
|
||||
}.execute(jpaQuery, new Object[] {}), is(nullValue()));
|
||||
}
|
||||
ModifyingExecution execution = new ModifyingExecution(method, em);
|
||||
execution.execute(jpaQuery, new Object[] {});
|
||||
|
||||
verify(em, times(1)).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void modifyingExecutionClearsEntityManagerIfSet() {
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void allowsMethodReturnTypesForModifyingQuery() throws Exception {
|
||||
|
||||
when(query.executeUpdate()).thenReturn(0);
|
||||
when(method.getReturnType()).thenReturn((Class) void.class);
|
||||
when(jpaQuery.createQuery(Mockito.any(Object[].class))).thenReturn(
|
||||
query);
|
||||
when(method.getReturnType()).thenReturn((Class) void.class, (Class) int.class, (Class) Integer.class);
|
||||
|
||||
ModifyingExecution execution = new ModifyingExecution(method, em);
|
||||
execution.execute(jpaQuery, new Object[] {});
|
||||
new ModifyingExecution(method, em);
|
||||
new ModifyingExecution(method, em);
|
||||
new ModifyingExecution(method, em);
|
||||
}
|
||||
|
||||
verify(em, times(1)).clear();
|
||||
}
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void modifyingExecutionRejectsNonIntegerOrVoidReturnType() throws Exception {
|
||||
|
||||
when(method.getReturnType()).thenReturn((Class) Long.class);
|
||||
new ModifyingExecution(method, em);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void allowsMethodReturnTypesForModifyingQuery() throws Exception {
|
||||
static class StubQueryExecution extends JpaQueryExecution {
|
||||
|
||||
when(method.getReturnType()).thenReturn((Class) void.class,
|
||||
(Class) int.class, (Class) Integer.class);
|
||||
@Override
|
||||
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
|
||||
|
||||
new ModifyingExecution(method, em);
|
||||
new ModifyingExecution(method, em);
|
||||
new ModifyingExecution(method, em);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void modifyingExecutionRejectsNonIntegerOrVoidReturnType()
|
||||
throws Exception {
|
||||
|
||||
when(method.getReturnType()).thenReturn((Class) Long.class);
|
||||
new ModifyingExecution(method, em);
|
||||
}
|
||||
|
||||
static class StubQueryExecution extends JpaQueryExecution {
|
||||
|
||||
@Override
|
||||
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
|
||||
import org.springframework.data.repository.query.QueryMethod;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link QueryMethod}.
|
||||
*
|
||||
@@ -47,230 +46,175 @@ import org.springframework.data.repository.query.QueryMethod;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JpaQueryMethodUnitTests {
|
||||
|
||||
static final Class<?> DOMAIN_CLASS = User.class;
|
||||
static final String METHOD_NAME = "findByFirstname";
|
||||
static final Class<?> DOMAIN_CLASS = User.class;
|
||||
static final String METHOD_NAME = "findByFirstname";
|
||||
|
||||
@Mock
|
||||
QueryExtractor extractor;
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
@Mock
|
||||
QueryExtractor extractor;
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
|
||||
Method repositoryMethod, invalidReturnType, pageableAndSort, pageableTwice,
|
||||
sortableTwice, modifyingMethod;
|
||||
Method repositoryMethod, invalidReturnType, pageableAndSort, pageableTwice, sortableTwice, modifyingMethod;
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
repositoryMethod = UserRepository.class.getMethod("findByLastname", String.class);
|
||||
|
||||
repositoryMethod =
|
||||
UserRepository.class.getMethod("findByLastname", String.class);
|
||||
invalidReturnType = InvalidRepository.class.getMethod(METHOD_NAME, String.class, Pageable.class);
|
||||
pageableAndSort = InvalidRepository.class.getMethod(METHOD_NAME, String.class, Pageable.class, Sort.class);
|
||||
pageableTwice = InvalidRepository.class.getMethod(METHOD_NAME, String.class, Pageable.class, Pageable.class);
|
||||
|
||||
invalidReturnType =
|
||||
InvalidRepository.class.getMethod(METHOD_NAME, String.class,
|
||||
Pageable.class);
|
||||
pageableAndSort =
|
||||
InvalidRepository.class.getMethod(METHOD_NAME, String.class,
|
||||
Pageable.class, Sort.class);
|
||||
pageableTwice =
|
||||
InvalidRepository.class.getMethod(METHOD_NAME, String.class,
|
||||
Pageable.class, Pageable.class);
|
||||
sortableTwice = InvalidRepository.class.getMethod(METHOD_NAME, String.class, Sort.class, Sort.class);
|
||||
modifyingMethod = UserRepository.class.getMethod("renameAllUsersTo", String.class);
|
||||
}
|
||||
|
||||
sortableTwice =
|
||||
InvalidRepository.class.getMethod(METHOD_NAME, String.class,
|
||||
Sort.class, Sort.class);
|
||||
modifyingMethod =
|
||||
UserRepository.class
|
||||
.getMethod("renameAllUsersTo", String.class);
|
||||
}
|
||||
@Test
|
||||
public void testname() {
|
||||
|
||||
JpaQueryMethod method = new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
|
||||
@Test
|
||||
public void testname() {
|
||||
assertEquals("User.findByLastname", method.getNamedQueryName());
|
||||
assertThat(method.isCollectionQuery(), is(true));
|
||||
}
|
||||
|
||||
JpaQueryMethod method =
|
||||
new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullRepositoryMethod() {
|
||||
|
||||
assertEquals("User.findByLastname", method.getNamedQueryName());
|
||||
assertThat(method.isCollectionQuery(), is(true));
|
||||
}
|
||||
new JpaQueryMethod(null, metadata, extractor);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullQueryExtractor() {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullRepositoryMethod() {
|
||||
new JpaQueryMethod(repositoryMethod, metadata, null);
|
||||
}
|
||||
|
||||
new JpaQueryMethod(null, metadata, extractor);
|
||||
}
|
||||
@Test
|
||||
public void returnsCorrectName() {
|
||||
|
||||
JpaQueryMethod method = new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
assertEquals(repositoryMethod.getName(), method.getName());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullQueryExtractor() {
|
||||
@Test
|
||||
public void returnsQueryIfAvailable() throws Exception {
|
||||
|
||||
new JpaQueryMethod(repositoryMethod, metadata, null);
|
||||
}
|
||||
JpaQueryMethod method = new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
|
||||
assertNull(method.getAnnotatedQuery());
|
||||
|
||||
@Test
|
||||
public void returnsCorrectName() {
|
||||
Method repositoryMethod = UserRepository.class.getMethod("findByAnnotatedQuery", String.class);
|
||||
|
||||
JpaQueryMethod method =
|
||||
new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
assertEquals(repositoryMethod.getName(), method.getName());
|
||||
}
|
||||
assertNotNull(new JpaQueryMethod(repositoryMethod, metadata, extractor).getAnnotatedQuery());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsInvalidReturntypeOnPagebleFinder() {
|
||||
|
||||
@Test
|
||||
public void returnsQueryIfAvailable() throws Exception {
|
||||
new JpaQueryMethod(invalidReturnType, metadata, extractor);
|
||||
}
|
||||
|
||||
JpaQueryMethod method =
|
||||
new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsPageableAndSortInFinderMethod() {
|
||||
|
||||
assertNull(method.getAnnotatedQuery());
|
||||
new JpaQueryMethod(pageableAndSort, metadata, extractor);
|
||||
}
|
||||
|
||||
Method repositoryMethod =
|
||||
UserRepository.class.getMethod("findByAnnotatedQuery",
|
||||
String.class);
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsTwoPageableParameters() {
|
||||
|
||||
assertNotNull(new JpaQueryMethod(repositoryMethod, metadata, extractor)
|
||||
.getAnnotatedQuery());
|
||||
}
|
||||
new JpaQueryMethod(pageableTwice, metadata, extractor);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsTwoSortableParameters() {
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsInvalidReturntypeOnPagebleFinder() {
|
||||
new JpaQueryMethod(sortableTwice, metadata, extractor);
|
||||
}
|
||||
|
||||
new JpaQueryMethod(invalidReturnType, metadata, extractor);
|
||||
}
|
||||
@Test
|
||||
public void recognizesModifyingMethod() {
|
||||
|
||||
JpaQueryMethod method = new JpaQueryMethod(modifyingMethod, metadata, extractor);
|
||||
assertTrue(method.isModifyingQuery());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsPageableAndSortInFinderMethod() {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsModifyingMethodWithPageable() throws Exception {
|
||||
|
||||
new JpaQueryMethod(pageableAndSort, metadata, extractor);
|
||||
}
|
||||
Method method = InvalidRepository.class.getMethod("updateMethod", String.class, Pageable.class);
|
||||
|
||||
new JpaQueryMethod(method, metadata, extractor);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsTwoPageableParameters() {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsModifyingMethodWithSort() throws Exception {
|
||||
|
||||
new JpaQueryMethod(pageableTwice, metadata, extractor);
|
||||
}
|
||||
Method method = InvalidRepository.class.getMethod("updateMethod", String.class, Sort.class);
|
||||
|
||||
new JpaQueryMethod(method, metadata, extractor);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsTwoSortableParameters() {
|
||||
@Test
|
||||
public void discoversHintsCorrectly() {
|
||||
|
||||
new JpaQueryMethod(sortableTwice, metadata, extractor);
|
||||
}
|
||||
JpaQueryMethod method = new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
List<QueryHint> hints = method.getHints();
|
||||
|
||||
assertNotNull(hints);
|
||||
assertThat(hints.get(0).name(), is("foo"));
|
||||
assertThat(hints.get(0).value(), is("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void recognizesModifyingMethod() {
|
||||
@Test
|
||||
public void calculatesNamedQueryNamesCorrectly() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
JpaQueryMethod method =
|
||||
new JpaQueryMethod(modifyingMethod, metadata, extractor);
|
||||
assertTrue(method.isModifyingQuery());
|
||||
}
|
||||
JpaQueryMethod queryMethod = new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
assertThat(queryMethod.getNamedQueryName(), is("User.findByLastname"));
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
|
||||
Method method = UserRepository.class.getMethod("renameAllUsersTo", String.class);
|
||||
queryMethod = new JpaQueryMethod(method, metadata, extractor);
|
||||
assertThat(queryMethod.getNamedQueryName(), is("User.renameAllUsersTo"));
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsModifyingMethodWithPageable() throws Exception {
|
||||
method = UserRepository.class.getMethod("findSpecialUsersByLastname", String.class);
|
||||
queryMethod = new JpaQueryMethod(method, metadata, extractor);
|
||||
assertThat(queryMethod.getNamedQueryName(), is("SpecialUser.findSpecialUsersByLastname"));
|
||||
}
|
||||
|
||||
Method method =
|
||||
InvalidRepository.class.getMethod("updateMethod", String.class,
|
||||
Pageable.class);
|
||||
/**
|
||||
* Interface to define invalid repository methods for testing.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
static interface InvalidRepository {
|
||||
|
||||
new JpaQueryMethod(method, metadata, extractor);
|
||||
}
|
||||
// Invalid return type
|
||||
User findByFirstname(String firstname, Pageable pageable);
|
||||
|
||||
// Should not use Pageable *and* Sort
|
||||
Page<User> findByFirstname(String firstname, Pageable pageable, Sort sort);
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsModifyingMethodWithSort() throws Exception {
|
||||
// Must not use two Pageables
|
||||
Page<User> findByFirstname(String firstname, Pageable first, Pageable second);
|
||||
|
||||
Method method =
|
||||
InvalidRepository.class.getMethod("updateMethod", String.class,
|
||||
Sort.class);
|
||||
// Must not use two Pageables
|
||||
Page<User> findByFirstname(String firstname, Sort first, Sort second);
|
||||
|
||||
new JpaQueryMethod(method, metadata, extractor);
|
||||
}
|
||||
// Not backed by a named query or @Query annotation
|
||||
@Modifying
|
||||
void updateMethod(String firstname);
|
||||
|
||||
// Modifying and Pageable is not allowed
|
||||
@Modifying
|
||||
Page<String> updateMethod(String firstname, Pageable pageable);
|
||||
|
||||
@Test
|
||||
public void discoversHintsCorrectly() {
|
||||
|
||||
JpaQueryMethod method =
|
||||
new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
List<QueryHint> hints = method.getHints();
|
||||
|
||||
assertNotNull(hints);
|
||||
assertThat(hints.get(0).name(), is("foo"));
|
||||
assertThat(hints.get(0).value(), is("bar"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void calculatesNamedQueryNamesCorrectly() throws SecurityException,
|
||||
NoSuchMethodException {
|
||||
|
||||
JpaQueryMethod queryMethod =
|
||||
new JpaQueryMethod(repositoryMethod, metadata, extractor);
|
||||
assertThat(queryMethod.getNamedQueryName(), is("User.findByLastname"));
|
||||
|
||||
RepositoryMetadata metadata =
|
||||
new DefaultRepositoryMetadata(UserRepository.class);
|
||||
Method method =
|
||||
UserRepository.class
|
||||
.getMethod("renameAllUsersTo", String.class);
|
||||
queryMethod = new JpaQueryMethod(method, metadata, extractor);
|
||||
assertThat(queryMethod.getNamedQueryName(), is("User.renameAllUsersTo"));
|
||||
|
||||
method =
|
||||
UserRepository.class.getMethod("findSpecialUsersByLastname",
|
||||
String.class);
|
||||
queryMethod = new JpaQueryMethod(method, metadata, extractor);
|
||||
assertThat(queryMethod.getNamedQueryName(),
|
||||
is("SpecialUser.findSpecialUsersByLastname"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface to define invalid repository methods for testing.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
static interface InvalidRepository {
|
||||
|
||||
// Invalid return type
|
||||
User findByFirstname(String firstname, Pageable pageable);
|
||||
|
||||
|
||||
// Should not use Pageable *and* Sort
|
||||
Page<User> findByFirstname(String firstname, Pageable pageable,
|
||||
Sort sort);
|
||||
|
||||
|
||||
// Must not use two Pageables
|
||||
Page<User> findByFirstname(String firstname, Pageable first,
|
||||
Pageable second);
|
||||
|
||||
|
||||
// Must not use two Pageables
|
||||
Page<User> findByFirstname(String firstname, Sort first, Sort second);
|
||||
|
||||
|
||||
// Not backed by a named query or @Query annotation
|
||||
@Modifying
|
||||
void updateMethod(String firstname);
|
||||
|
||||
|
||||
// Modifying and Pageable is not allowed
|
||||
@Modifying
|
||||
Page<String> updateMethod(String firstname, Pageable pageable);
|
||||
|
||||
|
||||
// Modifying and Sort is not allowed
|
||||
@Modifying
|
||||
void updateMethod(String firstname, Sort sort);
|
||||
}
|
||||
// Modifying and Sort is not allowed
|
||||
@Modifying
|
||||
void updateMethod(String firstname, Sort sort);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.query.QueryCreationException;
|
||||
|
||||
|
||||
/**
|
||||
* Unit tests for {@link NamedQuery}.
|
||||
*
|
||||
@@ -40,37 +39,34 @@ import org.springframework.data.repository.query.QueryCreationException;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NamedQueryUnitTests {
|
||||
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
@Mock
|
||||
QueryExtractor extractor;
|
||||
@Mock
|
||||
EntityManager em;
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
@Mock
|
||||
QueryExtractor extractor;
|
||||
@Mock
|
||||
EntityManager em;
|
||||
|
||||
Method method;
|
||||
Method method;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
@Before
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
method = SampleRepository.class.getMethod("foo", Pageable.class);
|
||||
when(metadata.getDomainClass()).thenReturn((Class) String.class);
|
||||
}
|
||||
|
||||
method = SampleRepository.class.getMethod("foo", Pageable.class);
|
||||
when(metadata.getDomainClass()).thenReturn((Class) String.class);
|
||||
}
|
||||
@Test(expected = QueryCreationException.class)
|
||||
public void rejectsPersistenceProviderIfIncapableOfExtractingQueriesAndPagebleBeingUsed() {
|
||||
|
||||
when(extractor.canExtractQuery()).thenReturn(false);
|
||||
|
||||
@Test(expected = QueryCreationException.class)
|
||||
public void rejectsPersistenceProviderIfIncapableOfExtractingQueriesAndPagebleBeingUsed() {
|
||||
JpaQueryMethod queryMethod = new JpaQueryMethod(method, metadata, extractor);
|
||||
NamedQuery.lookupFrom(queryMethod, em);
|
||||
}
|
||||
|
||||
when(extractor.canExtractQuery()).thenReturn(false);
|
||||
interface SampleRepository {
|
||||
|
||||
JpaQueryMethod queryMethod =
|
||||
new JpaQueryMethod(method, metadata, extractor);
|
||||
NamedQuery.lookupFrom(queryMethod, em);
|
||||
}
|
||||
|
||||
interface SampleRepository {
|
||||
|
||||
Page<String> foo(Pageable pageable);
|
||||
}
|
||||
Page<String> foo(Pageable pageable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,6 @@ import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.data.repository.query.Parameters;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link ParameterBinder}.
|
||||
*
|
||||
@@ -44,185 +43,146 @@ import org.springframework.data.repository.query.Parameters;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ParameterBinderUnitTests {
|
||||
|
||||
private Method valid;
|
||||
private Method valid;
|
||||
|
||||
@Mock
|
||||
private Query query;
|
||||
private Method useIndexedParameters;
|
||||
private Method indexedParametersWithSort;
|
||||
@Mock
|
||||
private Query query;
|
||||
private Method useIndexedParameters;
|
||||
private Method indexedParametersWithSort;
|
||||
|
||||
@Before
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
@Before
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
valid = SampleRepository.class.getMethod("valid", String.class);
|
||||
|
||||
valid = SampleRepository.class.getMethod("valid", String.class);
|
||||
useIndexedParameters = SampleRepository.class.getMethod("useIndexedParameters", String.class);
|
||||
indexedParametersWithSort = SampleRepository.class.getMethod("indexedParameterWithSort", String.class, Sort.class);
|
||||
}
|
||||
|
||||
useIndexedParameters =
|
||||
SampleRepository.class.getMethod("useIndexedParameters",
|
||||
String.class);
|
||||
indexedParametersWithSort =
|
||||
SampleRepository.class.getMethod("indexedParameterWithSort",
|
||||
String.class, Sort.class);
|
||||
}
|
||||
static class User {
|
||||
|
||||
static class User {
|
||||
}
|
||||
|
||||
}
|
||||
static interface SampleRepository {
|
||||
|
||||
static interface SampleRepository {
|
||||
User useIndexedParameters(String lastname);
|
||||
|
||||
User useIndexedParameters(String lastname);
|
||||
User indexedParameterWithSort(String lastname, Sort sort);
|
||||
|
||||
User valid(@Param("username") String username);
|
||||
|
||||
User indexedParameterWithSort(String lastname, Sort sort);
|
||||
User validWithPageable(@Param("username") String username, Pageable pageable);
|
||||
|
||||
User validWithSort(@Param("username") String username, Sort sort);
|
||||
}
|
||||
|
||||
User valid(@Param("username") String username);
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsToManyParameters() throws Exception {
|
||||
|
||||
new ParameterBinder(new Parameters(valid), new Object[] { "foo", "bar" });
|
||||
}
|
||||
|
||||
User validWithPageable(@Param("username") String username,
|
||||
Pageable pageable);
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullParameters() throws Exception {
|
||||
|
||||
new ParameterBinder(new Parameters(valid), (Object[]) null);
|
||||
}
|
||||
|
||||
User validWithSort(@Param("username") String username, Sort sort);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsToLittleParameters() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
Parameters parameters = new Parameters(valid);
|
||||
new ParameterBinder(parameters);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsToManyParameters() throws Exception {
|
||||
@Test
|
||||
public void returnsNullIfNoPageableWasProvided() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
new ParameterBinder(new Parameters(valid),
|
||||
new Object[] { "foo", "bar" });
|
||||
}
|
||||
Method method = SampleRepository.class.getMethod("validWithPageable", String.class, Pageable.class);
|
||||
|
||||
Parameters parameters = new Parameters(method);
|
||||
ParameterBinder binder = new ParameterBinder(parameters, new Object[] { "foo", null });
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullParameters() throws Exception {
|
||||
assertThat(binder.getPageable(), is(nullValue()));
|
||||
}
|
||||
|
||||
new ParameterBinder(new Parameters(valid), (Object[]) null);
|
||||
}
|
||||
@Test
|
||||
public void bindWorksWithNullForSort() throws Exception {
|
||||
|
||||
Method validWithSort = SampleRepository.class.getMethod("validWithSort", String.class, Sort.class);
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsToLittleParameters() throws SecurityException,
|
||||
NoSuchMethodException {
|
||||
new ParameterBinder(new Parameters(validWithSort), new Object[] { "foo", null }).bind(query);
|
||||
verify(query).setParameter(eq(1), eq("foo"));
|
||||
}
|
||||
|
||||
Parameters parameters = new Parameters(valid);
|
||||
new ParameterBinder(parameters);
|
||||
}
|
||||
@Test
|
||||
public void bindWorksWithNullForPageable() throws Exception {
|
||||
|
||||
Method validWithPageable = SampleRepository.class.getMethod("validWithPageable", String.class, Pageable.class);
|
||||
|
||||
@Test
|
||||
public void returnsNullIfNoPageableWasProvided() throws SecurityException,
|
||||
NoSuchMethodException {
|
||||
new ParameterBinder(new Parameters(validWithPageable), new Object[] { "foo", null }).bind(query);
|
||||
verify(query).setParameter(eq(1), eq("foo"));
|
||||
}
|
||||
|
||||
Method method =
|
||||
SampleRepository.class.getMethod("validWithPageable",
|
||||
String.class, Pageable.class);
|
||||
@Test
|
||||
public void usesIndexedParametersIfNoParamAnnotationPresent() throws Exception {
|
||||
|
||||
Parameters parameters = new Parameters(method);
|
||||
ParameterBinder binder =
|
||||
new ParameterBinder(parameters, new Object[] { "foo", null });
|
||||
new ParameterBinder(new Parameters(useIndexedParameters), new Object[] { "foo" }).bind(query);
|
||||
verify(query).setParameter(eq(1), anyObject());
|
||||
}
|
||||
|
||||
assertThat(binder.getPageable(), is(nullValue()));
|
||||
}
|
||||
@Test
|
||||
public void usesParameterNameIfAnnotated() throws Exception {
|
||||
|
||||
when(query.setParameter(eq("username"), anyObject())).thenReturn(query);
|
||||
new ParameterBinder(new Parameters(valid), new Object[] { "foo" }) {
|
||||
|
||||
@Test
|
||||
public void bindWorksWithNullForSort() throws Exception {
|
||||
@Override
|
||||
boolean hasNamedParameter(Query query) {
|
||||
|
||||
Method validWithSort =
|
||||
SampleRepository.class.getMethod("validWithSort", String.class,
|
||||
Sort.class);
|
||||
return true;
|
||||
}
|
||||
}.bind(query);
|
||||
verify(query).setParameter(eq("username"), anyObject());
|
||||
}
|
||||
|
||||
new ParameterBinder(new Parameters(validWithSort), new Object[] {
|
||||
"foo", null }).bind(query);
|
||||
verify(query).setParameter(eq(1), eq("foo"));
|
||||
}
|
||||
@Test
|
||||
public void bindsEmbeddableCorrectly() throws Exception {
|
||||
|
||||
Method method = getClass().getMethod("findByEmbeddable", SampleEmbeddable.class);
|
||||
Parameters parameters = new Parameters(method);
|
||||
SampleEmbeddable embeddable = new SampleEmbeddable();
|
||||
|
||||
@Test
|
||||
public void bindWorksWithNullForPageable() throws Exception {
|
||||
new ParameterBinder(parameters, new Object[] { embeddable }).bind(query);
|
||||
|
||||
Method validWithPageable =
|
||||
SampleRepository.class.getMethod("validWithPageable",
|
||||
String.class, Pageable.class);
|
||||
verify(query).setParameter(1, embeddable);
|
||||
}
|
||||
|
||||
new ParameterBinder(new Parameters(validWithPageable), new Object[] {
|
||||
"foo", null }).bind(query);
|
||||
verify(query).setParameter(eq(1), eq("foo"));
|
||||
}
|
||||
@Test
|
||||
public void bindsSortForIndexedParameters() throws Exception {
|
||||
|
||||
Sort sort = new Sort("name");
|
||||
ParameterBinder binder = new ParameterBinder(new Parameters(indexedParametersWithSort),
|
||||
new Object[] { "name", sort });
|
||||
assertThat(binder.getSort(), is(sort));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesIndexedParametersIfNoParamAnnotationPresent()
|
||||
throws Exception {
|
||||
public SampleEntity findByEmbeddable(SampleEmbeddable embeddable) {
|
||||
|
||||
new ParameterBinder(new Parameters(useIndexedParameters),
|
||||
new Object[] { "foo" }).bind(query);
|
||||
verify(query).setParameter(eq(1), anyObject());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static class SampleEntity {
|
||||
|
||||
@Test
|
||||
public void usesParameterNameIfAnnotated() throws Exception {
|
||||
private SampleEmbeddable embeddable;
|
||||
}
|
||||
|
||||
when(query.setParameter(eq("username"), anyObject())).thenReturn(query);
|
||||
new ParameterBinder(new Parameters(valid), new Object[] { "foo" }) {
|
||||
@Embeddable
|
||||
@SuppressWarnings("unused")
|
||||
public static class SampleEmbeddable {
|
||||
|
||||
@Override
|
||||
boolean hasNamedParameter(Query query) {
|
||||
|
||||
return true;
|
||||
}
|
||||
}.bind(query);
|
||||
verify(query).setParameter(eq("username"), anyObject());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void bindsEmbeddableCorrectly() throws Exception {
|
||||
|
||||
Method method =
|
||||
getClass()
|
||||
.getMethod("findByEmbeddable", SampleEmbeddable.class);
|
||||
Parameters parameters = new Parameters(method);
|
||||
SampleEmbeddable embeddable = new SampleEmbeddable();
|
||||
|
||||
new ParameterBinder(parameters, new Object[] { embeddable })
|
||||
.bind(query);
|
||||
|
||||
verify(query).setParameter(1, embeddable);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void bindsSortForIndexedParameters() throws Exception {
|
||||
|
||||
Sort sort = new Sort("name");
|
||||
ParameterBinder binder =
|
||||
new ParameterBinder(new Parameters(indexedParametersWithSort),
|
||||
new Object[] { "name", sort });
|
||||
assertThat(binder.getSort(), is(sort));
|
||||
}
|
||||
|
||||
|
||||
public SampleEntity findByEmbeddable(SampleEmbeddable embeddable) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static class SampleEntity {
|
||||
|
||||
private SampleEmbeddable embeddable;
|
||||
}
|
||||
|
||||
@Embeddable
|
||||
@SuppressWarnings("unused")
|
||||
public static class SampleEmbeddable {
|
||||
|
||||
private String foo;
|
||||
private String bar;
|
||||
}
|
||||
private String foo;
|
||||
private String bar;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.jpa.repository.query;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
@@ -36,7 +34,6 @@ import org.springframework.data.repository.core.support.DefaultRepositoryMetadat
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
|
||||
/**
|
||||
* Integration tests for {@link PartTreeJpaQuery}.
|
||||
*
|
||||
@@ -49,65 +46,58 @@ public class PartTreeJpaQueryIntegrationTests {
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@PersistenceContext
|
||||
EntityManager entityManager;
|
||||
@PersistenceContext
|
||||
EntityManager entityManager;
|
||||
|
||||
/**
|
||||
* @see DATADOC-90
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
|
||||
/**
|
||||
* @see DATADOC-90
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
Method method = UserRepository.class.getMethod("findByFirstname", String.class, Pageable.class);
|
||||
JpaQueryMethod queryMethod = new JpaQueryMethod(method, new DefaultRepositoryMetadata(UserRepository.class),
|
||||
PersistenceProvider.fromEntityManager(entityManager));
|
||||
PartTreeJpaQuery jpaQuery = new PartTreeJpaQuery(queryMethod, entityManager);
|
||||
|
||||
Method method =
|
||||
UserRepository.class.getMethod("findByFirstname", String.class,
|
||||
Pageable.class);
|
||||
JpaQueryMethod queryMethod =
|
||||
new JpaQueryMethod(method, new DefaultRepositoryMetadata(
|
||||
UserRepository.class),
|
||||
PersistenceProvider.fromEntityManager(entityManager));
|
||||
PartTreeJpaQuery jpaQuery =
|
||||
new PartTreeJpaQuery(queryMethod, entityManager);
|
||||
jpaQuery.createQuery(new Object[] { "Matthews", new PageRequest(0, 1) });
|
||||
jpaQuery.createQuery(new Object[] { "Matthews", new PageRequest(0, 1) });
|
||||
}
|
||||
|
||||
jpaQuery.createQuery(new Object[] { "Matthews", new PageRequest(0, 1) });
|
||||
jpaQuery.createQuery(new Object[] { "Matthews", new PageRequest(0, 1) });
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
public void cannotIgnoreCaseIfNotString() throws Exception {
|
||||
|
||||
thrown.expect(IllegalStateException.class);
|
||||
thrown.expectMessage("Unable to ignore case of java.lang.Integer types, the property 'id' must reference a String");
|
||||
testIgnoreCase("findByIdIgnoringCase", 3);
|
||||
|
||||
thrown.expect(IllegalStateException.class);
|
||||
thrown.expectMessage("Unable to ignore case of java.lang.Integer types, the property 'id' must reference a String");
|
||||
testIgnoreCase("findByIdIgnoringCase", 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
public void cannotIgnoreCaseIfNotStringUnlessIgnoringAll() throws Exception {
|
||||
|
||||
testIgnoreCase("findByIdAllIgnoringCase", 3);
|
||||
|
||||
testIgnoreCase("findByIdAllIgnoringCase", 3);
|
||||
}
|
||||
|
||||
private void testIgnoreCase(String methodName, Object...values) throws Exception {
|
||||
private void testIgnoreCase(String methodName, Object... values) throws Exception {
|
||||
|
||||
Class<?>[] parameterTypes = new Class[values.length];
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
Class<?>[] parameterTypes = new Class[values.length];
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
parameterTypes[i] = values[i].getClass();
|
||||
}
|
||||
Method method = UserRepository.class.getMethod(methodName, parameterTypes);
|
||||
JpaQueryMethod queryMethod =
|
||||
new JpaQueryMethod(method, new DefaultRepositoryMetadata(
|
||||
UserRepository.class),
|
||||
PersistenceProvider.fromEntityManager(entityManager));
|
||||
PartTreeJpaQuery jpaQuery =
|
||||
new PartTreeJpaQuery(queryMethod, entityManager);
|
||||
JpaQueryMethod queryMethod = new JpaQueryMethod(method, new DefaultRepositoryMetadata(UserRepository.class),
|
||||
PersistenceProvider.fromEntityManager(entityManager));
|
||||
PartTreeJpaQuery jpaQuery = new PartTreeJpaQuery(queryMethod, entityManager);
|
||||
jpaQuery.createQuery(values);
|
||||
}
|
||||
}
|
||||
|
||||
interface UserRepository extends Repository<User, Long> {
|
||||
interface UserRepository extends Repository<User, Long> {
|
||||
|
||||
Page<User> findByFirstname(String firstname, Pageable pageable);
|
||||
User findByIdIgnoringCase(Integer id);
|
||||
User findByIdAllIgnoringCase(Integer id);
|
||||
}
|
||||
Page<User> findByFirstname(String firstname, Pageable pageable);
|
||||
|
||||
User findByIdIgnoringCase(Integer id);
|
||||
|
||||
User findByIdAllIgnoringCase(Integer id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import static org.springframework.data.jpa.repository.query.QueryUtils.*;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link QueryUtils}.
|
||||
*
|
||||
@@ -30,129 +29,109 @@ import org.junit.Test;
|
||||
*/
|
||||
public class QueryUtilsUnitTests {
|
||||
|
||||
static final String QUERY = "select u from User u";
|
||||
static final String FQ_QUERY =
|
||||
"select u from org.acme.domain.User$Foo_Bar u";
|
||||
static final String SIMPLE_QUERY = "from User u";
|
||||
static final String COUNT_QUERY = "select count(u) from User u";
|
||||
static final String QUERY = "select u from User u";
|
||||
static final String FQ_QUERY = "select u from org.acme.domain.User$Foo_Bar u";
|
||||
static final String SIMPLE_QUERY = "from User u";
|
||||
static final String COUNT_QUERY = "select count(u) from User u";
|
||||
|
||||
static final String QUERY_WITH_AS =
|
||||
"select u from User as u where u.username = ?";
|
||||
static final String QUERY_WITH_AS = "select u from User as u where u.username = ?";
|
||||
|
||||
static final Matcher<String> IS_U = is("u");
|
||||
static final Matcher<String> IS_U = is("u");
|
||||
|
||||
@Test
|
||||
public void createsCountQueryCorrectly() throws Exception {
|
||||
|
||||
@Test
|
||||
public void createsCountQueryCorrectly() throws Exception {
|
||||
assertCountQuery(QUERY, COUNT_QUERY);
|
||||
|
||||
assertCountQuery(QUERY, COUNT_QUERY);
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* @see #303
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueriesCorrectlyForCapitalLetterJPQL() {
|
||||
|
||||
assertCountQuery("FROM User u WHERE u.foo.bar = ?", "select count(u) FROM User u WHERE u.foo.bar = ?");
|
||||
|
||||
/**
|
||||
* @see #303
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueriesCorrectlyForCapitalLetterJPQL() {
|
||||
assertCountQuery("SELECT u FROM User u where u.foo.bar = ?", "select count(u) FROM User u where u.foo.bar = ?");
|
||||
}
|
||||
|
||||
assertCountQuery("FROM User u WHERE u.foo.bar = ?",
|
||||
"select count(u) FROM User u WHERE u.foo.bar = ?");
|
||||
/**
|
||||
* @see #351
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForDistinctQueries() throws Exception {
|
||||
|
||||
assertCountQuery("SELECT u FROM User u where u.foo.bar = ?",
|
||||
"select count(u) FROM User u where u.foo.bar = ?");
|
||||
}
|
||||
assertCountQuery("select distinct u from User u where u.foo = ?",
|
||||
"select count(distinct u) from User u where u.foo = ?");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #351
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForConstructorQueries() throws Exception {
|
||||
|
||||
/**
|
||||
* @see #351
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForDistinctQueries() throws Exception {
|
||||
assertCountQuery("select distinct new User(u.name) from User u where u.foo = ?",
|
||||
"select count(distinct u) from User u where u.foo = ?");
|
||||
}
|
||||
|
||||
assertCountQuery("select distinct u from User u where u.foo = ?",
|
||||
"select count(distinct u) from User u where u.foo = ?");
|
||||
}
|
||||
/**
|
||||
* @see #352
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForJoins() throws Exception {
|
||||
|
||||
assertCountQuery("select distinct new User(u.name) from User u left outer join u.roles r WHERE r = ?",
|
||||
"select count(distinct u) from User u left outer join u.roles r WHERE r = ?");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #351
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForConstructorQueries() throws Exception {
|
||||
/**
|
||||
* @see #352
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForQueriesWithSubSelects() throws Exception {
|
||||
|
||||
assertCountQuery(
|
||||
"select distinct new User(u.name) from User u where u.foo = ?",
|
||||
"select count(distinct u) from User u where u.foo = ?");
|
||||
}
|
||||
assertCountQuery("select u from User u left outer join u.roles r where r in (select r from Role)",
|
||||
"select count(u) from User u left outer join u.roles r where r in (select r from Role)");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #355
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForAliasesCorrectly() throws Exception {
|
||||
|
||||
/**
|
||||
* @see #352
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForJoins() throws Exception {
|
||||
assertCountQuery("select u from User as u", "select count(u) from User as u");
|
||||
}
|
||||
|
||||
assertCountQuery(
|
||||
"select distinct new User(u.name) from User u left outer join u.roles r WHERE r = ?",
|
||||
"select count(distinct u) from User u left outer join u.roles r WHERE r = ?");
|
||||
}
|
||||
@Test
|
||||
public void allowsShortJpaSyntax() throws Exception {
|
||||
|
||||
assertCountQuery(SIMPLE_QUERY, COUNT_QUERY);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #352
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForQueriesWithSubSelects() throws Exception {
|
||||
@Test
|
||||
public void detectsAliasCorrectly() throws Exception {
|
||||
|
||||
assertCountQuery(
|
||||
"select u from User u left outer join u.roles r where r in (select r from Role)",
|
||||
"select count(u) from User u left outer join u.roles r where r in (select r from Role)");
|
||||
}
|
||||
assertThat(detectAlias(QUERY), IS_U);
|
||||
assertThat(detectAlias(SIMPLE_QUERY), IS_U);
|
||||
assertThat(detectAlias(COUNT_QUERY), IS_U);
|
||||
assertThat(detectAlias(QUERY_WITH_AS), IS_U);
|
||||
assertThat(detectAlias("SELECT FROM USER U"), is("U"));
|
||||
assertThat(detectAlias("select u from User u"), IS_U);
|
||||
assertThat(detectAlias("select u from com.acme.User u"), IS_U);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowsFullyQualifiedEntityNamesInQuery() {
|
||||
|
||||
/**
|
||||
* @see #355
|
||||
*/
|
||||
@Test
|
||||
public void createsCountQueryForAliasesCorrectly() throws Exception {
|
||||
assertThat(detectAlias(FQ_QUERY), IS_U);
|
||||
assertCountQuery(FQ_QUERY, "select count(u) from org.acme.domain.User$Foo_Bar u");
|
||||
}
|
||||
|
||||
assertCountQuery("select u from User as u",
|
||||
"select count(u) from User as u");
|
||||
}
|
||||
private void assertCountQuery(String originalQuery, String countQuery) {
|
||||
|
||||
|
||||
@Test
|
||||
public void allowsShortJpaSyntax() throws Exception {
|
||||
|
||||
assertCountQuery(SIMPLE_QUERY, COUNT_QUERY);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void detectsAliasCorrectly() throws Exception {
|
||||
|
||||
assertThat(detectAlias(QUERY), IS_U);
|
||||
assertThat(detectAlias(SIMPLE_QUERY), IS_U);
|
||||
assertThat(detectAlias(COUNT_QUERY), IS_U);
|
||||
assertThat(detectAlias(QUERY_WITH_AS), IS_U);
|
||||
assertThat(detectAlias("SELECT FROM USER U"), is("U"));
|
||||
assertThat(detectAlias("select u from User u"), IS_U);
|
||||
assertThat(detectAlias("select u from com.acme.User u"), IS_U);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void allowsFullyQualifiedEntityNamesInQuery() {
|
||||
|
||||
assertThat(detectAlias(FQ_QUERY), IS_U);
|
||||
assertCountQuery(FQ_QUERY,
|
||||
"select count(u) from org.acme.domain.User$Foo_Bar u");
|
||||
}
|
||||
|
||||
|
||||
private void assertCountQuery(String originalQuery, String countQuery) {
|
||||
|
||||
assertThat(createCountQueryFor(originalQuery), is(countQuery));
|
||||
}
|
||||
assertThat(createCountQueryFor(originalQuery), is(countQuery));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,6 @@ import org.springframework.data.jpa.repository.sample.UserRepository;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.query.Parameters;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link SimpleJpaQuery}.
|
||||
*
|
||||
@@ -48,79 +47,67 @@ import org.springframework.data.repository.query.Parameters;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SimpleJpaQueryUnitTests {
|
||||
|
||||
JpaQueryMethod method;
|
||||
JpaQueryMethod method;
|
||||
|
||||
@Mock
|
||||
EntityManager em;
|
||||
@Mock
|
||||
QueryExtractor extractor;
|
||||
@Mock
|
||||
Query query;
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
@Mock
|
||||
ParameterBinder binder;
|
||||
@Mock
|
||||
EntityManager em;
|
||||
@Mock
|
||||
QueryExtractor extractor;
|
||||
@Mock
|
||||
Query query;
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
@Mock
|
||||
ParameterBinder binder;
|
||||
|
||||
@Before
|
||||
@QueryHints(@QueryHint(name = "foo", value = "bar"))
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
@Before
|
||||
@QueryHints(@QueryHint(name = "foo", value = "bar"))
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
when(em.createQuery(anyString())).thenReturn(query);
|
||||
|
||||
when(em.createQuery(anyString())).thenReturn(query);
|
||||
Method setUp = UserRepository.class.getMethod("findByLastname", String.class);
|
||||
method = new JpaQueryMethod(setUp, metadata, extractor);
|
||||
}
|
||||
|
||||
Method setUp =
|
||||
UserRepository.class.getMethod("findByLastname", String.class);
|
||||
method = new JpaQueryMethod(setUp, metadata, extractor);
|
||||
}
|
||||
@Test
|
||||
public void appliesHintsCorrectly() throws Exception {
|
||||
|
||||
SimpleJpaQuery jpaQuery = new SimpleJpaQuery(method, em, "foobar");
|
||||
jpaQuery.createQuery(new Object[] { "gierke" });
|
||||
|
||||
@Test
|
||||
public void appliesHintsCorrectly() throws Exception {
|
||||
verify(query).setHint("foo", "bar");
|
||||
}
|
||||
|
||||
SimpleJpaQuery jpaQuery = new SimpleJpaQuery(method, em, "foobar");
|
||||
jpaQuery.createQuery(new Object[] { "gierke" });
|
||||
@Test
|
||||
public void prefersDeclaredCountQueryOverCreatingOne() throws Exception {
|
||||
|
||||
verify(query).setHint("foo", "bar");
|
||||
}
|
||||
method = mock(JpaQueryMethod.class);
|
||||
when(method.getCountQuery()).thenReturn("foo");
|
||||
when(method.getParameters()).thenReturn(
|
||||
new Parameters(SimpleJpaQueryUnitTests.class.getMethod("prefersDeclaredCountQueryOverCreatingOne")));
|
||||
when(em.createQuery("foo")).thenReturn(query);
|
||||
|
||||
SimpleJpaQuery jpaQuery = new SimpleJpaQuery(method, em, "select u from User u");
|
||||
|
||||
@Test
|
||||
public void prefersDeclaredCountQueryOverCreatingOne() throws Exception {
|
||||
assertThat(jpaQuery.createCountQuery(new Object[] {}), is(query));
|
||||
}
|
||||
|
||||
method = mock(JpaQueryMethod.class);
|
||||
when(method.getCountQuery()).thenReturn("foo");
|
||||
when(method.getParameters())
|
||||
.thenReturn(
|
||||
new Parameters(
|
||||
SimpleJpaQueryUnitTests.class
|
||||
.getMethod("prefersDeclaredCountQueryOverCreatingOne")));
|
||||
when(em.createQuery("foo")).thenReturn(query);
|
||||
/**
|
||||
* @see DATAJPA-77
|
||||
*/
|
||||
@Test
|
||||
public void doesNotApplyPaginationToCountQuery() throws Exception {
|
||||
|
||||
SimpleJpaQuery jpaQuery =
|
||||
new SimpleJpaQuery(method, em, "select u from User u");
|
||||
when(em.createQuery(Mockito.anyString())).thenReturn(query);
|
||||
|
||||
assertThat(jpaQuery.createCountQuery(new Object[] {}), is(query));
|
||||
}
|
||||
Method method = UserRepository.class.getMethod("findAllPaged", Pageable.class);
|
||||
JpaQueryMethod queryMethod = new JpaQueryMethod(method, metadata, extractor);
|
||||
|
||||
AbstractJpaQuery jpaQuery = new SimpleJpaQuery(queryMethod, em, "select u from User u");
|
||||
jpaQuery.createCountQuery(new Object[] { new PageRequest(1, 10) });
|
||||
|
||||
/**
|
||||
* @see DATAJPA-77
|
||||
*/
|
||||
@Test
|
||||
public void doesNotApplyPaginationToCountQuery() throws Exception {
|
||||
|
||||
when(em.createQuery(Mockito.anyString())).thenReturn(query);
|
||||
|
||||
Method method =
|
||||
UserRepository.class.getMethod("findAllPaged", Pageable.class);
|
||||
JpaQueryMethod queryMethod =
|
||||
new JpaQueryMethod(method, metadata, extractor);
|
||||
|
||||
AbstractJpaQuery jpaQuery =
|
||||
new SimpleJpaQuery(queryMethod, em, "select u from User u");
|
||||
jpaQuery.createCountQuery(new Object[] { new PageRequest(1, 10) });
|
||||
|
||||
verify(query, times(0)).setFirstResult(anyInt());
|
||||
verify(query, times(0)).setMaxResults(anyInt());
|
||||
}
|
||||
verify(query, times(0)).setFirstResult(anyInt());
|
||||
verify(query, times(0)).setMaxResults(anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,20 +20,18 @@ import java.util.List;
|
||||
import org.springframework.data.jpa.domain.sample.AuditableUser;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
|
||||
/**
|
||||
* Repository interface for {@code AuditableUser}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface AuditableUserRepository extends
|
||||
JpaRepository<AuditableUser, Long> {
|
||||
public interface AuditableUserRepository extends JpaRepository<AuditableUser, Long> {
|
||||
|
||||
/**
|
||||
* Returns all users with the given firstname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return all users with the given firstname.
|
||||
*/
|
||||
public List<AuditableUser> findByFirstname(final String firstname);
|
||||
/**
|
||||
* Returns all users with the given firstname.
|
||||
*
|
||||
* @param firstname
|
||||
* @return all users with the given firstname.
|
||||
*/
|
||||
public List<AuditableUser> findByFirstname(final String firstname);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ package org.springframework.data.jpa.repository.sample;
|
||||
import org.springframework.data.jpa.domain.sample.Role;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
|
||||
/**
|
||||
* Typing interface for {@code Role}.
|
||||
*
|
||||
|
||||
@@ -34,199 +34,155 @@ import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Repository interface for {@code User}s.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface UserRepository extends JpaRepository<User, Integer>,
|
||||
JpaSpecificationExecutor<User>, UserRepositoryCustom {
|
||||
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User>,
|
||||
UserRepositoryCustom {
|
||||
|
||||
/**
|
||||
* Retrieve users by their lastname. The finder
|
||||
* {@literal User.findByLastname} is declared in {@literal META-INF/orm.xml}
|
||||
* .
|
||||
*
|
||||
* @param lastname
|
||||
* @return all users with the given lastname
|
||||
*/
|
||||
@QueryHints({ @QueryHint(name = "foo", value = "bar") })
|
||||
List<User> findByLastname(String lastname);
|
||||
/**
|
||||
* Retrieve users by their lastname. The finder {@literal User.findByLastname} is declared in
|
||||
* {@literal META-INF/orm.xml} .
|
||||
*
|
||||
* @param lastname
|
||||
* @return all users with the given lastname
|
||||
*/
|
||||
@QueryHints({ @QueryHint(name = "foo", value = "bar") })
|
||||
List<User> findByLastname(String lastname);
|
||||
|
||||
/**
|
||||
* Redeclaration of {@link CrudRepository#findOne(java.io.Serializable)} to change transaction configuration.
|
||||
*/
|
||||
@Transactional
|
||||
public User findOne(Integer primaryKey);
|
||||
|
||||
/**
|
||||
* Redeclaration of {@link CrudRepository#findOne(java.io.Serializable)} to
|
||||
* change transaction configuration.
|
||||
*/
|
||||
@Transactional
|
||||
public User findOne(Integer primaryKey);
|
||||
/**
|
||||
* Retrieve users by their email address. The finder {@literal User.findByEmailAddress} is declared as annotation at
|
||||
* {@code User}.
|
||||
*
|
||||
* @param emailAddress
|
||||
* @return the user with the given email address
|
||||
*/
|
||||
User findByEmailAddress(String emailAddress);
|
||||
|
||||
@Query("select u from User u ")
|
||||
Page<User> findAllPaged(Pageable pageable);
|
||||
|
||||
/**
|
||||
* Retrieve users by their email address. The finder
|
||||
* {@literal User.findByEmailAddress} is declared as annotation at
|
||||
* {@code User}.
|
||||
*
|
||||
* @param emailAddress
|
||||
* @return the user with the given email address
|
||||
*/
|
||||
User findByEmailAddress(String emailAddress);
|
||||
/**
|
||||
* Retrieves users by the given email and lastname. Acts as a dummy method declaration to test finder query creation.
|
||||
*
|
||||
* @param emailAddress
|
||||
* @param lastname
|
||||
* @return the user with the given email address and lastname
|
||||
*/
|
||||
User findByEmailAddressAndLastname(String emailAddress, String lastname);
|
||||
|
||||
/**
|
||||
* Retrieves users by email address and lastname or firstname. Acts as a dummy method declaration to test finder query
|
||||
* creation.
|
||||
*
|
||||
* @param emailAddress
|
||||
* @param lastname
|
||||
* @param username
|
||||
* @return the users with the given email address and lastname or the given firstname
|
||||
*/
|
||||
List<User> findByEmailAddressAndLastnameOrFirstname(String emailAddress, String lastname, String username);
|
||||
|
||||
@Query("select u from User u ")
|
||||
Page<User> findAllPaged(Pageable pageable);
|
||||
/**
|
||||
* Retrieves a user by its username using the query annotated to the method.
|
||||
*
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
@Query("select u from User u where u.emailAddress = ?1")
|
||||
@Transactional(readOnly = true)
|
||||
User findByAnnotatedQuery(String emailAddress);
|
||||
|
||||
/**
|
||||
* Method to directly create query from and adding a {@link Pageable} parameter to be regarded on query execution.
|
||||
*
|
||||
* @param pageable
|
||||
* @param lastname
|
||||
* @return
|
||||
*/
|
||||
Page<User> findByLastname(Pageable pageable, String lastname);
|
||||
|
||||
/**
|
||||
* Retrieves users by the given email and lastname. Acts as a dummy method
|
||||
* declaration to test finder query creation.
|
||||
*
|
||||
* @param emailAddress
|
||||
* @param lastname
|
||||
* @return the user with the given email address and lastname
|
||||
*/
|
||||
User findByEmailAddressAndLastname(String emailAddress, String lastname);
|
||||
/**
|
||||
* Method to directly create query from and adding a {@link Pageable} parameter to be regarded on query execution.
|
||||
* Just returns the queried {@link Page}'s contents.
|
||||
*
|
||||
* @param firstname
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
List<User> findByFirstname(String firstname, Pageable pageable);
|
||||
|
||||
Page<User> findByFirstnameIn(Pageable pageable, String... firstnames);
|
||||
|
||||
/**
|
||||
* Retrieves users by email address and lastname or firstname. Acts as a
|
||||
* dummy method declaration to test finder query creation.
|
||||
*
|
||||
* @param emailAddress
|
||||
* @param lastname
|
||||
* @param username
|
||||
* @return the users with the given email address and lastname or the given
|
||||
* firstname
|
||||
*/
|
||||
List<User> findByEmailAddressAndLastnameOrFirstname(String emailAddress,
|
||||
String lastname, String username);
|
||||
List<User> findByFirstnameNotIn(Collection<String> firstnames);
|
||||
|
||||
/**
|
||||
* Manipulating query to set all {@link User}'s names to the given one.
|
||||
*
|
||||
* @param lastname
|
||||
*/
|
||||
@Modifying
|
||||
@Query("update User u set u.lastname = ?1")
|
||||
void renameAllUsersTo(String lastname);
|
||||
|
||||
/**
|
||||
* Retrieves a user by its username using the query annotated to the method.
|
||||
*
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
@Query("select u from User u where u.emailAddress = ?1")
|
||||
@Transactional(readOnly = true)
|
||||
User findByAnnotatedQuery(String emailAddress);
|
||||
@Query("select count(u) from User u where u.firstname = ?1")
|
||||
Long countWithFirstname(String firstname);
|
||||
|
||||
/**
|
||||
* Method where parameters will be applied by name. Note that the order of the parameters is then not crucial anymore.
|
||||
*
|
||||
* @param firstname
|
||||
* @param lastname
|
||||
* @return
|
||||
*/
|
||||
@Query("select u from User u where u.lastname = :lastname or u.firstname = :firstname")
|
||||
List<User> findByLastnameOrFirstname(@Param("firstname") String foo, @Param("lastname") String bar);
|
||||
|
||||
/**
|
||||
* Method to directly create query from and adding a {@link Pageable}
|
||||
* parameter to be regarded on query execution.
|
||||
*
|
||||
* @param pageable
|
||||
* @param lastname
|
||||
* @return
|
||||
*/
|
||||
Page<User> findByLastname(Pageable pageable, String lastname);
|
||||
@Query("select u from User u where u.lastname = :lastname or u.firstname = :firstname")
|
||||
List<User> findByLastnameOrFirstnameUnannotated(String firstname, String lastname);
|
||||
|
||||
/**
|
||||
* Method to check query creation and named parameter usage go well hand in hand.
|
||||
*
|
||||
* @param lastname
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
List<User> findByFirstnameOrLastname(@Param("lastname") String lastname, @Param("firstname") String firstname);
|
||||
|
||||
/**
|
||||
* Method to directly create query from and adding a {@link Pageable}
|
||||
* parameter to be regarded on query execution. Just returns the queried
|
||||
* {@link Page}'s contents.
|
||||
*
|
||||
* @param firstname
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
List<User> findByFirstname(String firstname, Pageable pageable);
|
||||
List<User> findByLastnameLikeOrderByFirstnameDesc(String lastname);
|
||||
|
||||
List<User> findByLastnameNotLike(String lastname);
|
||||
|
||||
Page<User> findByFirstnameIn(Pageable pageable, String... firstnames);
|
||||
List<User> findByLastnameNot(String lastname);
|
||||
|
||||
List<User> findByManagerLastname(String name);
|
||||
|
||||
List<User> findByFirstnameNotIn(Collection<String> firstnames);
|
||||
List<User> findByColleaguesLastname(String lastname);
|
||||
|
||||
List<User> findByLastnameNotNull();
|
||||
|
||||
/**
|
||||
* Manipulating query to set all {@link User}'s names to the given one.
|
||||
*
|
||||
* @param lastname
|
||||
*/
|
||||
@Modifying
|
||||
@Query("update User u set u.lastname = ?1")
|
||||
void renameAllUsersTo(String lastname);
|
||||
List<User> findByLastnameNull();
|
||||
|
||||
List<User> findByEmailAddressLike(String email, Sort sort);
|
||||
|
||||
@Query("select count(u) from User u where u.firstname = ?1")
|
||||
Long countWithFirstname(String firstname);
|
||||
List<SpecialUser> findSpecialUsersByLastname(String lastname);
|
||||
|
||||
List<User> findBySpringDataNamedQuery(String lastname);
|
||||
|
||||
/**
|
||||
* Method where parameters will be applied by name. Note that the order of
|
||||
* the parameters is then not crucial anymore.
|
||||
*
|
||||
* @param firstname
|
||||
* @param lastname
|
||||
* @return
|
||||
*/
|
||||
@Query("select u from User u where u.lastname = :lastname or u.firstname = :firstname")
|
||||
List<User> findByLastnameOrFirstname(@Param("firstname") String foo,
|
||||
@Param("lastname") String bar);
|
||||
List<User> findByLastnameIgnoringCase(String lastname);
|
||||
|
||||
Page<User> findByLastnameIgnoringCase(Pageable pageable, String lastname);
|
||||
|
||||
@Query("select u from User u where u.lastname = :lastname or u.firstname = :firstname")
|
||||
List<User> findByLastnameOrFirstnameUnannotated(String firstname,
|
||||
String lastname);
|
||||
List<User> findByLastnameIgnoringCaseLike(String lastname);
|
||||
|
||||
|
||||
/**
|
||||
* Method to check query creation and named parameter usage go well hand in
|
||||
* hand.
|
||||
*
|
||||
* @param lastname
|
||||
* @param firstname
|
||||
* @return
|
||||
*/
|
||||
List<User> findByFirstnameOrLastname(@Param("lastname") String lastname,
|
||||
@Param("firstname") String firstname);
|
||||
|
||||
|
||||
List<User> findByLastnameLikeOrderByFirstnameDesc(String lastname);
|
||||
|
||||
|
||||
List<User> findByLastnameNotLike(String lastname);
|
||||
|
||||
|
||||
List<User> findByLastnameNot(String lastname);
|
||||
|
||||
|
||||
List<User> findByManagerLastname(String name);
|
||||
|
||||
|
||||
List<User> findByColleaguesLastname(String lastname);
|
||||
|
||||
|
||||
List<User> findByLastnameNotNull();
|
||||
|
||||
|
||||
List<User> findByLastnameNull();
|
||||
|
||||
|
||||
List<User> findByEmailAddressLike(String email, Sort sort);
|
||||
|
||||
|
||||
List<SpecialUser> findSpecialUsersByLastname(String lastname);
|
||||
|
||||
|
||||
List<User> findBySpringDataNamedQuery(String lastname);
|
||||
|
||||
|
||||
List<User> findByLastnameIgnoringCase(String lastname);
|
||||
|
||||
|
||||
Page<User> findByLastnameIgnoringCase(Pageable pageable, String lastname);
|
||||
|
||||
|
||||
List<User> findByLastnameIgnoringCaseLike(String lastname);
|
||||
|
||||
|
||||
List<User> findByLastnameAndFirstnameAllIgnoringCase(String lastname,
|
||||
String firstname);
|
||||
List<User> findByLastnameAndFirstnameAllIgnoringCase(String lastname, String firstname);
|
||||
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ package org.springframework.data.jpa.repository.sample;
|
||||
|
||||
import org.springframework.data.jpa.domain.sample.User;
|
||||
|
||||
|
||||
/**
|
||||
* Simple interface for custom methods on the repository for {@code User}s.
|
||||
*
|
||||
@@ -25,16 +24,15 @@ import org.springframework.data.jpa.domain.sample.User;
|
||||
*/
|
||||
public interface UserRepositoryCustom {
|
||||
|
||||
/**
|
||||
* Method actually triggering a finder but being overridden.
|
||||
*/
|
||||
void findByOverrridingMethod();
|
||||
/**
|
||||
* Method actually triggering a finder but being overridden.
|
||||
*/
|
||||
void findByOverrridingMethod();
|
||||
|
||||
|
||||
/**
|
||||
* Some custom method to implement.
|
||||
*
|
||||
* @param user
|
||||
*/
|
||||
void someCustomMethod(User user);
|
||||
/**
|
||||
* Some custom method to implement.
|
||||
*
|
||||
* @param user
|
||||
*/
|
||||
void someCustomMethod(User user);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.jpa.domain.sample.User;
|
||||
|
||||
|
||||
/**
|
||||
* Dummy implementation to allow check for invoking a custom implementation.
|
||||
*
|
||||
@@ -27,30 +26,27 @@ import org.springframework.data.jpa.domain.sample.User;
|
||||
*/
|
||||
public class UserRepositoryImpl implements UserRepositoryCustom {
|
||||
|
||||
private static final Logger LOG = LoggerFactory
|
||||
.getLogger(UserRepositoryImpl.class);
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UserRepositoryImpl.class);
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.repository.sample.UserRepositoryCustom#
|
||||
* someCustomMethod(org.springframework.data.jpa.domain.sample.User)
|
||||
*/
|
||||
public void someCustomMethod(User u) {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.repository.sample.UserRepositoryCustom#
|
||||
* someCustomMethod(org.springframework.data.jpa.domain.sample.User)
|
||||
*/
|
||||
public void someCustomMethod(User u) {
|
||||
LOG.debug("Some custom method was invoked!");
|
||||
}
|
||||
|
||||
LOG.debug("Some custom method was invoked!");
|
||||
}
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.repository.sample.UserRepositoryCustom#
|
||||
* findByOverrridingMethod()
|
||||
*/
|
||||
public void findByOverrridingMethod() {
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.jpa.repository.sample.UserRepositoryCustom#
|
||||
* findByOverrridingMethod()
|
||||
*/
|
||||
public void findByOverrridingMethod() {
|
||||
|
||||
LOG.debug("A method overriding a finder was invoked!");
|
||||
}
|
||||
LOG.debug("A method overriding a finder was invoked!");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,10 +28,8 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Assures the injected repository instances are wired to the customly
|
||||
* configured {@link EntityManagerFactory}.
|
||||
* Assures the injected repository instances are wired to the customly configured {@link EntityManagerFactory}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@@ -39,26 +37,23 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@ContextConfiguration(locations = "classpath:multiple-entity-manager-integration-context.xml")
|
||||
public class EntityManagerFactoryRefTests {
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
AuditableUserRepository auditableUserRepository;
|
||||
@Autowired
|
||||
AuditableUserRepository auditableUserRepository;
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void useUserRepository() throws Exception {
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void useUserRepository() throws Exception {
|
||||
userRepository.saveAndFlush(new User("firstname", "lastname", "foo@bar.de"));
|
||||
}
|
||||
|
||||
userRepository.saveAndFlush(new User("firstname", "lastname",
|
||||
"foo@bar.de"));
|
||||
}
|
||||
@Test
|
||||
@Transactional("transactionManager-2")
|
||||
public void useAuditableUserRepository() throws Exception {
|
||||
|
||||
|
||||
@Test
|
||||
@Transactional("transactionManager-2")
|
||||
public void useAuditableUserRepository() throws Exception {
|
||||
|
||||
auditableUserRepository.saveAndFlush(new AuditableUser());
|
||||
}
|
||||
auditableUserRepository.saveAndFlush(new AuditableUser());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,47 +26,36 @@ import org.springframework.beans.factory.config.BeanReference;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
|
||||
/**
|
||||
* Assures the injected repository instances are wired to the customly
|
||||
* configured {@link EntityManagerFactory}.
|
||||
* Assures the injected repository instances are wired to the customly configured {@link EntityManagerFactory}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class EntityManagerFactoryRefUnitTests {
|
||||
|
||||
@Test
|
||||
public void repositoriesGetTheSecondEntityManagerFactoryInjected2() {
|
||||
@Test
|
||||
public void repositoriesGetTheSecondEntityManagerFactoryInjected2() {
|
||||
|
||||
XmlBeanFactory factory =
|
||||
new XmlBeanFactory(new ClassPathResource(
|
||||
"multiple-entity-manager-context.xml"));
|
||||
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("multiple-entity-manager-context.xml"));
|
||||
|
||||
BeanDefinition bean = factory.getBeanDefinition("userRepository");
|
||||
Object value = getPropertyValue(bean, "entityManager");
|
||||
assertTrue(value instanceof BeanDefinition);
|
||||
BeanDefinition emCreator = (BeanDefinition) value;
|
||||
BeanDefinition bean = factory.getBeanDefinition("userRepository");
|
||||
Object value = getPropertyValue(bean, "entityManager");
|
||||
assertTrue(value instanceof BeanDefinition);
|
||||
BeanDefinition emCreator = (BeanDefinition) value;
|
||||
|
||||
BeanReference reference = getConstructorBeanReference(emCreator, 0);
|
||||
assertThat(reference.getBeanName(), is("secondEntityManagerFactory"));
|
||||
}
|
||||
BeanReference reference = getConstructorBeanReference(emCreator, 0);
|
||||
assertThat(reference.getBeanName(), is("secondEntityManagerFactory"));
|
||||
}
|
||||
|
||||
private Object getPropertyValue(BeanDefinition definition, String propertyName) {
|
||||
|
||||
private Object getPropertyValue(BeanDefinition definition,
|
||||
String propertyName) {
|
||||
return definition.getPropertyValues().getPropertyValue(propertyName).getValue();
|
||||
}
|
||||
|
||||
return definition.getPropertyValues().getPropertyValue(propertyName)
|
||||
.getValue();
|
||||
}
|
||||
private BeanReference getConstructorBeanReference(BeanDefinition definition, int index) {
|
||||
|
||||
|
||||
private BeanReference getConstructorBeanReference(
|
||||
BeanDefinition definition, int index) {
|
||||
|
||||
Object value =
|
||||
definition.getConstructorArgumentValues()
|
||||
.getIndexedArgumentValues().get(index).getValue();
|
||||
assertTrue(value instanceof BeanReference);
|
||||
return (BeanReference) value;
|
||||
}
|
||||
Object value = definition.getConstructorArgumentValues().getIndexedArgumentValues().get(index).getValue();
|
||||
assertTrue(value instanceof BeanReference);
|
||||
return (BeanReference) value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AbstractJpaEntityInformation}.
|
||||
*
|
||||
@@ -35,52 +34,45 @@ import org.mockito.runners.MockitoJUnitRunner;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JpaEntityInformationSupportUnitTests {
|
||||
|
||||
@Test
|
||||
public void usesSimpleClassNameIfNoEntityNameGiven() throws Exception {
|
||||
@Test
|
||||
public void usesSimpleClassNameIfNoEntityNameGiven() throws Exception {
|
||||
|
||||
JpaEntityInformation<User, Long> information =
|
||||
new DummyJpaEntityInformation<User, Long>(User.class);
|
||||
assertEquals("User", information.getEntityName());
|
||||
JpaEntityInformation<User, Long> information = new DummyJpaEntityInformation<User, Long>(User.class);
|
||||
assertEquals("User", information.getEntityName());
|
||||
|
||||
JpaEntityInformation<NamedUser, ?> second =
|
||||
new DummyJpaEntityInformation<NamedUser, Serializable>(
|
||||
NamedUser.class);
|
||||
assertEquals("AnotherNamedUser", second.getEntityName());
|
||||
}
|
||||
JpaEntityInformation<NamedUser, ?> second = new DummyJpaEntityInformation<NamedUser, Serializable>(NamedUser.class);
|
||||
assertEquals("AnotherNamedUser", second.getEntityName());
|
||||
}
|
||||
|
||||
static class User {
|
||||
static class User {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Entity(name = "AnotherNamedUser")
|
||||
public class NamedUser {
|
||||
@Entity(name = "AnotherNamedUser")
|
||||
public class NamedUser {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
static class DummyJpaEntityInformation<T, ID extends Serializable> extends
|
||||
JpaEntityInformationSupport<T, ID> {
|
||||
static class DummyJpaEntityInformation<T, ID extends Serializable> extends JpaEntityInformationSupport<T, ID> {
|
||||
|
||||
public DummyJpaEntityInformation(Class<T> domainClass) {
|
||||
public DummyJpaEntityInformation(Class<T> domainClass) {
|
||||
|
||||
super(domainClass);
|
||||
}
|
||||
super(domainClass);
|
||||
}
|
||||
|
||||
public SingularAttribute<? super T, ?> getIdAttribute() {
|
||||
|
||||
public SingularAttribute<? super T, ?> getIdAttribute() {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
public ID getId(T entity) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public ID getId(T entity) {
|
||||
public Class<ID> getIdType() {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public Class<ID> getIdType() {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.domain.Persistable;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
|
||||
|
||||
/**
|
||||
* Unit tests for {@link JpaPersistableEntityInformation}.
|
||||
*
|
||||
@@ -40,57 +39,52 @@ import org.springframework.data.repository.core.EntityInformation;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JpaPersistableEntityInformationUnitTests {
|
||||
|
||||
@Mock
|
||||
Metamodel metamodel;
|
||||
@Mock
|
||||
Metamodel metamodel;
|
||||
|
||||
@Mock
|
||||
EntityType<Foo> type;
|
||||
@Mock
|
||||
EntityType<Foo> type;
|
||||
|
||||
@Mock
|
||||
@SuppressWarnings("rawtypes")
|
||||
Type idType;
|
||||
@Mock
|
||||
@SuppressWarnings("rawtypes")
|
||||
Type idType;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
when(metamodel.entity(Foo.class)).thenReturn(type);
|
||||
when(type.getIdType()).thenReturn(idType);
|
||||
}
|
||||
|
||||
when(metamodel.entity(Foo.class)).thenReturn(type);
|
||||
when(type.getIdType()).thenReturn(idType);
|
||||
}
|
||||
@Test
|
||||
public void usesPersistableMethodsForIsNewAndGetId() {
|
||||
|
||||
EntityInformation<Foo, Long> entityInformation = new JpaPersistableEntityInformation<Foo, Long>(Foo.class,
|
||||
metamodel);
|
||||
|
||||
@Test
|
||||
public void usesPersistableMethodsForIsNewAndGetId() {
|
||||
Foo foo = new Foo();
|
||||
assertThat(entityInformation.isNew(foo), is(false));
|
||||
assertThat(entityInformation.getId(foo), is(nullValue()));
|
||||
|
||||
EntityInformation<Foo, Long> entityInformation =
|
||||
new JpaPersistableEntityInformation<Foo, Long>(Foo.class,
|
||||
metamodel);
|
||||
foo.id = 1L;
|
||||
assertThat(entityInformation.isNew(foo), is(true));
|
||||
assertThat(entityInformation.getId(foo), is(1L));
|
||||
}
|
||||
|
||||
Foo foo = new Foo();
|
||||
assertThat(entityInformation.isNew(foo), is(false));
|
||||
assertThat(entityInformation.getId(foo), is(nullValue()));
|
||||
@SuppressWarnings("serial")
|
||||
class Foo implements Persistable<Long> {
|
||||
|
||||
foo.id = 1L;
|
||||
assertThat(entityInformation.isNew(foo), is(true));
|
||||
assertThat(entityInformation.getId(foo), is(1L));
|
||||
}
|
||||
Long id;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
class Foo implements Persistable<Long> {
|
||||
public Long getId() {
|
||||
|
||||
Long id;
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
|
||||
public Long getId() {
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
public boolean isNew() {
|
||||
|
||||
return id != null;
|
||||
}
|
||||
}
|
||||
return id != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,131 +38,114 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@code JpaRepositoryFactoryBean}.
|
||||
* <p>
|
||||
* TODO: Check if test methods double the ones in
|
||||
* {@link JpaRepositoryFactoryUnitTests}.
|
||||
* TODO: Check if test methods double the ones in {@link JpaRepositoryFactoryUnitTests}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JpaRepositoryFactoryBeanUnitTests {
|
||||
|
||||
JpaRepositoryFactoryBean<SimpleSampleRepository, User, Integer> factoryBean;
|
||||
JpaRepositoryFactoryBean<SimpleSampleRepository, User, Integer> factoryBean;
|
||||
|
||||
@Mock
|
||||
EntityManager entityManager;
|
||||
@Mock
|
||||
RepositoryFactorySupport factory;
|
||||
@Mock
|
||||
ListableBeanFactory beanFactory;
|
||||
@Mock
|
||||
PersistenceExceptionTranslator translator;
|
||||
@Mock
|
||||
Repository<?, ?> repository;
|
||||
@Mock
|
||||
EntityManager entityManager;
|
||||
@Mock
|
||||
RepositoryFactorySupport factory;
|
||||
@Mock
|
||||
ListableBeanFactory beanFactory;
|
||||
@Mock
|
||||
PersistenceExceptionTranslator translator;
|
||||
@Mock
|
||||
Repository<?, ?> repository;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
Map<String, PersistenceExceptionTranslator> beans = new HashMap<String, PersistenceExceptionTranslator>();
|
||||
beans.put("foo", translator);
|
||||
when(beanFactory.getBeansOfType(eq(PersistenceExceptionTranslator.class), anyBoolean(), anyBoolean())).thenReturn(
|
||||
beans);
|
||||
when(factory.getRepository(any(Class.class), any(Object.class))).thenReturn(repository);
|
||||
|
||||
Map<String, PersistenceExceptionTranslator> beans =
|
||||
new HashMap<String, PersistenceExceptionTranslator>();
|
||||
beans.put("foo", translator);
|
||||
when(
|
||||
beanFactory.getBeansOfType(
|
||||
eq(PersistenceExceptionTranslator.class), anyBoolean(),
|
||||
anyBoolean())).thenReturn(beans);
|
||||
when(factory.getRepository(any(Class.class), any(Object.class)))
|
||||
.thenReturn(repository);
|
||||
// Setup standard factory configuration
|
||||
factoryBean = new DummyJpaRepositoryFactoryBean<SimpleSampleRepository, User, Integer>();
|
||||
factoryBean.setRepositoryInterface(SimpleSampleRepository.class);
|
||||
factoryBean.setEntityManager(entityManager);
|
||||
}
|
||||
|
||||
// Setup standard factory configuration
|
||||
factoryBean =
|
||||
new DummyJpaRepositoryFactoryBean<SimpleSampleRepository, User, Integer>();
|
||||
factoryBean.setRepositoryInterface(SimpleSampleRepository.class);
|
||||
factoryBean.setEntityManager(entityManager);
|
||||
}
|
||||
/**
|
||||
* Assert that the instance created for the standard configuration is a valid {@code UserRepository}.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void setsUpBasicInstanceCorrectly() throws Exception {
|
||||
|
||||
factoryBean.setBeanFactory(beanFactory);
|
||||
factoryBean.afterPropertiesSet();
|
||||
|
||||
/**
|
||||
* Assert that the instance created for the standard configuration is a
|
||||
* valid {@code UserRepository}.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void setsUpBasicInstanceCorrectly() throws Exception {
|
||||
assertNotNull(factoryBean.getObject());
|
||||
}
|
||||
|
||||
factoryBean.setBeanFactory(beanFactory);
|
||||
factoryBean.afterPropertiesSet();
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void requiresListableBeanFactory() throws Exception {
|
||||
|
||||
assertNotNull(factoryBean.getObject());
|
||||
}
|
||||
factoryBean.setBeanFactory(mock(BeanFactory.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the factory rejects calls to {@code JpaRepositoryFactoryBean#setRepositoryInterface(Class)} with
|
||||
* {@literal null} or any other parameter instance not implementing {@code Repository}.
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullRepositoryInterface() {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void requiresListableBeanFactory() throws Exception {
|
||||
factoryBean.setRepositoryInterface(null);
|
||||
}
|
||||
|
||||
factoryBean.setBeanFactory(mock(BeanFactory.class));
|
||||
}
|
||||
/**
|
||||
* Assert that the factory detects unset repository class and interface in
|
||||
* {@code JpaRepositoryFactoryBean#afterPropertiesSet()}.
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsUnsetRepositoryInterface() throws Exception {
|
||||
|
||||
factoryBean = new JpaRepositoryFactoryBean<SimpleSampleRepository, User, Integer>();
|
||||
factoryBean.afterPropertiesSet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the factory rejects calls to
|
||||
* {@code JpaRepositoryFactoryBean#setRepositoryInterface(Class)} with
|
||||
* {@literal null} or any other parameter instance not implementing
|
||||
* {@code Repository}.
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullRepositoryInterface() {
|
||||
private class DummyJpaRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable> extends
|
||||
JpaRepositoryFactoryBean<T, S, ID> {
|
||||
|
||||
factoryBean.setRepositoryInterface(null);
|
||||
}
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean
|
||||
* #createRepositoryFactory()
|
||||
*/
|
||||
@Override
|
||||
protected RepositoryFactorySupport doCreateRepositoryFactory() {
|
||||
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the factory detects unset repository class and interface in
|
||||
* {@code JpaRepositoryFactoryBean#afterPropertiesSet()}.
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsUnsetRepositoryInterface() throws Exception {
|
||||
private interface SimpleSampleRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
factoryBean =
|
||||
new JpaRepositoryFactoryBean<SimpleSampleRepository, User, Integer>();
|
||||
factoryBean.afterPropertiesSet();
|
||||
}
|
||||
}
|
||||
|
||||
private class DummyJpaRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable>
|
||||
extends JpaRepositoryFactoryBean<T, S, ID> {
|
||||
/**
|
||||
* Helper class to make the factory use {@link PersistableMetadata} .
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
private static abstract class User implements Persistable<Long> {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean
|
||||
* #createRepositoryFactory()
|
||||
*/
|
||||
@Override
|
||||
protected RepositoryFactorySupport doCreateRepositoryFactory() {
|
||||
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
|
||||
private interface SimpleSampleRepository extends
|
||||
JpaRepository<User, Integer> {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper class to make the factory use {@link PersistableMetadata} .
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
private static abstract class User implements Persistable<Long> {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ import org.springframework.data.querydsl.QueryDslPredicateExecutor;
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@code JpaRepositoryFactory}.
|
||||
*
|
||||
@@ -47,177 +46,146 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JpaRepositoryFactoryUnitTests {
|
||||
|
||||
JpaRepositoryFactory factory;
|
||||
JpaRepositoryFactory factory;
|
||||
|
||||
@Mock
|
||||
EntityManager entityManager;
|
||||
@Mock
|
||||
@SuppressWarnings("rawtypes")
|
||||
JpaEntityInformation metadata;
|
||||
@Mock
|
||||
EntityManager entityManager;
|
||||
@Mock
|
||||
@SuppressWarnings("rawtypes")
|
||||
JpaEntityInformation metadata;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
// Setup standard factory configuration
|
||||
factory = new JpaRepositoryFactory(entityManager) {
|
||||
|
||||
// Setup standard factory configuration
|
||||
factory = new JpaRepositoryFactory(entityManager) {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T, ID extends Serializable> JpaEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T, ID extends Serializable> JpaEntityInformation<T, ID> getEntityInformation(
|
||||
Class<T> domainClass) {
|
||||
return metadata;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
return metadata;
|
||||
};
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Assert that the instance created for the standard configuration is a valid {@code UserRepository}.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void setsUpBasicInstanceCorrectly() throws Exception {
|
||||
|
||||
assertNotNull(factory.getRepository(SimpleSampleRepository.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the instance created for the standard configuration is a
|
||||
* valid {@code UserRepository}.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void setsUpBasicInstanceCorrectly() throws Exception {
|
||||
@Test
|
||||
public void allowsCallingOfObjectMethods() {
|
||||
|
||||
assertNotNull(factory.getRepository(SimpleSampleRepository.class));
|
||||
}
|
||||
SimpleSampleRepository repository = factory.getRepository(SimpleSampleRepository.class);
|
||||
|
||||
repository.hashCode();
|
||||
repository.toString();
|
||||
repository.equals(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowsCallingOfObjectMethods() {
|
||||
/**
|
||||
* Asserts that the factory recognized configured repository classes that contain custom method but no custom
|
||||
* implementation could be found. Furthremore the exception has to contain the name of the repository interface as for
|
||||
* a large repository configuration it's hard to find out where this error occured.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void capturesMissingCustomImplementationAndProvidesInterfacename() throws Exception {
|
||||
|
||||
SimpleSampleRepository repository =
|
||||
factory.getRepository(SimpleSampleRepository.class);
|
||||
try {
|
||||
factory.getRepository(SampleRepository.class);
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertTrue(e.getMessage().contains(SampleRepository.class.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
repository.hashCode();
|
||||
repository.toString();
|
||||
repository.equals(repository);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void handlesRuntimeExceptionsCorrectly() {
|
||||
|
||||
SampleRepository repository = factory.getRepository(SampleRepository.class, new SampleCustomRepositoryImpl());
|
||||
repository.throwingRuntimeException();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the factory recognized configured repository classes that
|
||||
* contain custom method but no custom implementation could be found.
|
||||
* Furthremore the exception has to contain the name of the repository
|
||||
* interface as for a large repository configuration it's hard to find out
|
||||
* where this error occured.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void capturesMissingCustomImplementationAndProvidesInterfacename()
|
||||
throws Exception {
|
||||
@Test(expected = IOException.class)
|
||||
public void handlesCheckedExceptionsCorrectly() throws Exception {
|
||||
|
||||
try {
|
||||
factory.getRepository(SampleRepository.class);
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertTrue(e.getMessage()
|
||||
.contains(SampleRepository.class.getName()));
|
||||
}
|
||||
}
|
||||
SampleRepository repository = factory.getRepository(SampleRepository.class, new SampleCustomRepositoryImpl());
|
||||
repository.throwingCheckedException();
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void createsProxyWithCustomBaseClass() {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void handlesRuntimeExceptionsCorrectly() {
|
||||
JpaRepositoryFactory factory = new CustomGenericJpaRepositoryFactory(entityManager);
|
||||
UserCustomExtendedRepository repository = factory.getRepository(UserCustomExtendedRepository.class);
|
||||
|
||||
SampleRepository repository =
|
||||
factory.getRepository(SampleRepository.class,
|
||||
new SampleCustomRepositoryImpl());
|
||||
repository.throwingRuntimeException();
|
||||
}
|
||||
repository.customMethod(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesQueryDslRepositoryIfInterfaceImplementsExecutor() {
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void handlesCheckedExceptionsCorrectly() throws Exception {
|
||||
when(metadata.getJavaType()).thenReturn(User.class);
|
||||
assertEquals(QueryDslJpaRepository.class,
|
||||
factory.getRepositoryBaseClass(new DefaultRepositoryMetadata(QueryDslSampleRepository.class)));
|
||||
|
||||
SampleRepository repository =
|
||||
factory.getRepository(SampleRepository.class,
|
||||
new SampleCustomRepositoryImpl());
|
||||
repository.throwingCheckedException();
|
||||
}
|
||||
try {
|
||||
QueryDslSampleRepository repository = factory.getRepository(QueryDslSampleRepository.class);
|
||||
assertEquals(QueryDslJpaRepository.class, ((Advised) repository).getTargetClass());
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertThat(e.getStackTrace()[0].getClassName(), is("org.springframework.data.querydsl.SimpleEntityPathResolver"));
|
||||
}
|
||||
}
|
||||
|
||||
private interface SimpleSampleRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void createsProxyWithCustomBaseClass() {
|
||||
@Transactional
|
||||
User findOne(Integer id);
|
||||
}
|
||||
|
||||
JpaRepositoryFactory factory =
|
||||
new CustomGenericJpaRepositoryFactory(entityManager);
|
||||
UserCustomExtendedRepository repository =
|
||||
factory.getRepository(UserCustomExtendedRepository.class);
|
||||
/**
|
||||
* Sample interface to contain a custom method.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface SampleCustomRepository {
|
||||
|
||||
repository.customMethod(1);
|
||||
}
|
||||
void throwingRuntimeException();
|
||||
|
||||
void throwingCheckedException() throws IOException;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesQueryDslRepositoryIfInterfaceImplementsExecutor() {
|
||||
/**
|
||||
* Implementation of the custom repository interface.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
private class SampleCustomRepositoryImpl implements SampleCustomRepository {
|
||||
|
||||
when(metadata.getJavaType()).thenReturn(User.class);
|
||||
assertEquals(QueryDslJpaRepository.class,
|
||||
factory.getRepositoryBaseClass(new DefaultRepositoryMetadata(
|
||||
QueryDslSampleRepository.class)));
|
||||
public void throwingRuntimeException() {
|
||||
|
||||
try {
|
||||
QueryDslSampleRepository repository =
|
||||
factory.getRepository(QueryDslSampleRepository.class);
|
||||
assertEquals(QueryDslJpaRepository.class,
|
||||
((Advised) repository).getTargetClass());
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertThat(
|
||||
e.getStackTrace()[0].getClassName(),
|
||||
is("org.springframework.data.querydsl.SimpleEntityPathResolver"));
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("You lose!");
|
||||
}
|
||||
|
||||
private interface SimpleSampleRepository extends
|
||||
JpaRepository<User, Integer> {
|
||||
public void throwingCheckedException() throws IOException {
|
||||
|
||||
@Transactional
|
||||
User findOne(Integer id);
|
||||
}
|
||||
throw new IOException("You lose!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample interface to contain a custom method.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface SampleCustomRepository {
|
||||
private interface SampleRepository extends JpaRepository<User, Integer>, SampleCustomRepository {
|
||||
|
||||
void throwingRuntimeException();
|
||||
}
|
||||
|
||||
private interface QueryDslSampleRepository extends SimpleSampleRepository, QueryDslPredicateExecutor<User> {
|
||||
|
||||
void throwingCheckedException() throws IOException;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implementation of the custom repository interface.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
private class SampleCustomRepositoryImpl implements SampleCustomRepository {
|
||||
|
||||
public void throwingRuntimeException() {
|
||||
|
||||
throw new IllegalArgumentException("You lose!");
|
||||
}
|
||||
|
||||
|
||||
public void throwingCheckedException() throws IOException {
|
||||
|
||||
throw new IOException("You lose!");
|
||||
}
|
||||
}
|
||||
|
||||
private interface SampleRepository extends JpaRepository<User, Integer>,
|
||||
SampleCustomRepository {
|
||||
|
||||
}
|
||||
|
||||
private interface QueryDslSampleRepository extends SimpleSampleRepository,
|
||||
QueryDslPredicateExecutor<User> {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for {@link JpaRepository}.
|
||||
*
|
||||
@@ -44,37 +43,31 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Transactional
|
||||
public class JpaRepositoryTests {
|
||||
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
|
||||
JpaRepository<SampleEntity, SampleEntityPK> repository;
|
||||
JpaRepository<SampleEntity, SampleEntityPK> repository;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
repository = new JpaRepositoryFactory(em).getRepository(SampleEntityRepository.class);
|
||||
}
|
||||
|
||||
repository =
|
||||
new JpaRepositoryFactory(em)
|
||||
.getRepository(SampleEntityRepository.class);
|
||||
}
|
||||
@Test
|
||||
public void testCrudOperationsForCompoundKeyEntity() throws Exception {
|
||||
|
||||
SampleEntity entity = new SampleEntity("foo", "bar");
|
||||
repository.saveAndFlush(entity);
|
||||
assertThat(repository.count(), is(1L));
|
||||
assertThat(repository.findOne(new SampleEntityPK("foo", "bar")), is(entity));
|
||||
|
||||
@Test
|
||||
public void testCrudOperationsForCompoundKeyEntity() throws Exception {
|
||||
repository.delete(Arrays.asList(entity));
|
||||
repository.flush();
|
||||
assertThat(repository.count(), is(0L));
|
||||
}
|
||||
|
||||
SampleEntity entity = new SampleEntity("foo", "bar");
|
||||
repository.saveAndFlush(entity);
|
||||
assertThat(repository.count(), is(1L));
|
||||
assertThat(repository.findOne(new SampleEntityPK("foo", "bar")),
|
||||
is(entity));
|
||||
private static interface SampleEntityRepository extends JpaRepository<SampleEntity, SampleEntityPK> {
|
||||
|
||||
repository.delete(Arrays.asList(entity));
|
||||
repository.flush();
|
||||
assertThat(repository.count(), is(0L));
|
||||
}
|
||||
|
||||
private static interface SampleEntityRepository extends
|
||||
JpaRepository<SampleEntity, SampleEntityPK> {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,5 +22,5 @@ package org.springframework.data.jpa.repository.support;
|
||||
*/
|
||||
class QSimpleEntityPathResolverUnitTests_Sample {
|
||||
|
||||
public QSimpleEntityPathResolverUnitTests_Sample field;
|
||||
public QSimpleEntityPathResolverUnitTests_Sample field;
|
||||
}
|
||||
|
||||
@@ -36,7 +36,6 @@ import com.mysema.query.types.expr.BooleanExpression;
|
||||
import com.mysema.query.types.path.PathBuilder;
|
||||
import com.mysema.query.types.path.PathBuilderFactory;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for {@link QueryDslJpaRepository}.
|
||||
*
|
||||
@@ -47,57 +46,47 @@ import com.mysema.query.types.path.PathBuilderFactory;
|
||||
@Transactional
|
||||
public class QueryDslJpaRepositoryTests {
|
||||
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
|
||||
QueryDslJpaRepository<User, Integer> repository;
|
||||
QUser user = new QUser("user");
|
||||
User dave, carter;
|
||||
QueryDslJpaRepository<User, Integer> repository;
|
||||
QUser user = new QUser("user");
|
||||
User dave, carter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
JpaEntityInformation<User, Integer> information = new JpaMetamodelEntityInformation<User, Integer>(User.class,
|
||||
em.getMetamodel());
|
||||
|
||||
JpaEntityInformation<User, Integer> information =
|
||||
new JpaMetamodelEntityInformation<User, Integer>(User.class,
|
||||
em.getMetamodel());
|
||||
repository = new QueryDslJpaRepository<User, Integer>(information, em);
|
||||
dave = repository.save(new User("Dave", "Matthews", "dave@matthews.com"));
|
||||
carter = repository.save(new User("Carter", "Beauford", "carter@beauford.com"));
|
||||
}
|
||||
|
||||
repository = new QueryDslJpaRepository<User, Integer>(information, em);
|
||||
dave =
|
||||
repository.save(new User("Dave", "Matthews",
|
||||
"dave@matthews.com"));
|
||||
carter =
|
||||
repository.save(new User("Carter", "Beauford",
|
||||
"carter@beauford.com"));
|
||||
}
|
||||
@Test
|
||||
public void executesPredicatesCorrectly() throws Exception {
|
||||
|
||||
BooleanExpression isCalledDave = user.firstname.eq("Dave");
|
||||
BooleanExpression isBeauford = user.lastname.eq("Beauford");
|
||||
|
||||
@Test
|
||||
public void executesPredicatesCorrectly() throws Exception {
|
||||
List<User> result = repository.findAll(isCalledDave.or(isBeauford));
|
||||
|
||||
BooleanExpression isCalledDave = user.firstname.eq("Dave");
|
||||
BooleanExpression isBeauford = user.lastname.eq("Beauford");
|
||||
assertThat(result.size(), is(2));
|
||||
assertThat(result, hasItems(carter, dave));
|
||||
}
|
||||
|
||||
List<User> result = repository.findAll(isCalledDave.or(isBeauford));
|
||||
@Test
|
||||
public void executesStringBasedPredicatesCorrectly() throws Exception {
|
||||
|
||||
assertThat(result.size(), is(2));
|
||||
assertThat(result, hasItems(carter, dave));
|
||||
}
|
||||
PathBuilder<User> builder = new PathBuilderFactory().create(User.class);
|
||||
|
||||
BooleanExpression isCalledDave = builder.getString("firstname").eq("Dave");
|
||||
BooleanExpression isBeauford = builder.getString("lastname").eq("Beauford");
|
||||
|
||||
@Test
|
||||
public void executesStringBasedPredicatesCorrectly() throws Exception {
|
||||
List<User> result = repository.findAll(isCalledDave.or(isBeauford));
|
||||
|
||||
PathBuilder<User> builder = new PathBuilderFactory().create(User.class);
|
||||
|
||||
BooleanExpression isCalledDave =
|
||||
builder.getString("firstname").eq("Dave");
|
||||
BooleanExpression isBeauford =
|
||||
builder.getString("lastname").eq("Beauford");
|
||||
|
||||
List<User> result = repository.findAll(isCalledDave.or(isBeauford));
|
||||
|
||||
assertThat(result.size(), is(2));
|
||||
assertThat(result, hasItems(carter, dave));
|
||||
}
|
||||
assertThat(result.size(), is(2));
|
||||
assertThat(result, hasItems(carter, dave));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for {@link QueryDslRepositorySupport}.
|
||||
*
|
||||
@@ -28,115 +27,104 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Transactional
|
||||
public class QueryDslRepositorySupportTests {
|
||||
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
@PersistenceContext
|
||||
EntityManager em;
|
||||
|
||||
UserRepository repository;
|
||||
User dave, carter;
|
||||
UserRepository repository;
|
||||
User dave, carter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
dave = new User("Dave", "Matthews", "dave@matthews.com");
|
||||
em.persist(dave);
|
||||
|
||||
dave = new User("Dave", "Matthews", "dave@matthews.com");
|
||||
em.persist(dave);
|
||||
carter = new User("Carter", "Beauford", "carter@beauford.com");
|
||||
em.persist(carter);
|
||||
|
||||
carter = new User("Carter", "Beauford", "carter@beauford.com");
|
||||
em.persist(carter);
|
||||
UserRepositoryImpl repository = new UserRepositoryImpl();
|
||||
repository.setEntityManager(em);
|
||||
repository.validate();
|
||||
|
||||
UserRepositoryImpl repository = new UserRepositoryImpl();
|
||||
repository.setEntityManager(em);
|
||||
repository.validate();
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
this.repository = repository;
|
||||
}
|
||||
@Test
|
||||
public void readsUsersCorrectly() throws Exception {
|
||||
|
||||
List<User> result = repository.findUsersByLastname("Matthews");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(dave));
|
||||
|
||||
@Test
|
||||
public void readsUsersCorrectly() throws Exception {
|
||||
result = repository.findUsersByLastname("Beauford");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
|
||||
List<User> result = repository.findUsersByLastname("Matthews");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(dave));
|
||||
@Test
|
||||
public void updatesUsersCorrectly() throws Exception {
|
||||
|
||||
result = repository.findUsersByLastname("Beauford");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
long updates = repository.updateLastnamesTo("Foo");
|
||||
assertThat(updates, is(2L));
|
||||
|
||||
List<User> result = repository.findUsersByLastname("Matthews");
|
||||
assertThat(result.size(), is(0));
|
||||
|
||||
@Test
|
||||
public void updatesUsersCorrectly() throws Exception {
|
||||
result = repository.findUsersByLastname("Beauford");
|
||||
assertThat(result.size(), is(0));
|
||||
|
||||
long updates = repository.updateLastnamesTo("Foo");
|
||||
assertThat(updates, is(2L));
|
||||
result = repository.findUsersByLastname("Foo");
|
||||
assertThat(result.size(), is(2));
|
||||
assertThat(result, hasItems(dave, carter));
|
||||
}
|
||||
|
||||
List<User> result = repository.findUsersByLastname("Matthews");
|
||||
assertThat(result.size(), is(0));
|
||||
@Test
|
||||
public void deletesAllWithLastnameCorrectly() throws Exception {
|
||||
|
||||
result = repository.findUsersByLastname("Beauford");
|
||||
assertThat(result.size(), is(0));
|
||||
long updates = repository.deleteAllWithLastname("Matthews");
|
||||
assertThat(updates, is(1L));
|
||||
|
||||
result = repository.findUsersByLastname("Foo");
|
||||
assertThat(result.size(), is(2));
|
||||
assertThat(result, hasItems(dave, carter));
|
||||
}
|
||||
List<User> result = repository.findUsersByLastname("Matthews");
|
||||
assertThat(result.size(), is(0));
|
||||
|
||||
result = repository.findUsersByLastname("Beauford");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deletesAllWithLastnameCorrectly() throws Exception {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsUnsetEntityManager() throws Exception {
|
||||
|
||||
long updates = repository.deleteAllWithLastname("Matthews");
|
||||
assertThat(updates, is(1L));
|
||||
UserRepositoryImpl repositoryImpl = new UserRepositoryImpl();
|
||||
repositoryImpl.validate();
|
||||
}
|
||||
|
||||
List<User> result = repository.findUsersByLastname("Matthews");
|
||||
assertThat(result.size(), is(0));
|
||||
private static interface UserRepository {
|
||||
|
||||
result = repository.findUsersByLastname("Beauford");
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0), is(carter));
|
||||
}
|
||||
List<User> findUsersByLastname(String firstname);
|
||||
|
||||
long updateLastnamesTo(String lastname);
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsUnsetEntityManager() throws Exception {
|
||||
long deleteAllWithLastname(String lastname);
|
||||
}
|
||||
|
||||
UserRepositoryImpl repositoryImpl = new UserRepositoryImpl();
|
||||
repositoryImpl.validate();
|
||||
}
|
||||
private static class UserRepositoryImpl extends QueryDslRepositorySupport implements UserRepository {
|
||||
|
||||
private static interface UserRepository {
|
||||
private static final QUser user = QUser.user;
|
||||
|
||||
List<User> findUsersByLastname(String firstname);
|
||||
public List<User> findUsersByLastname(String lastname) {
|
||||
|
||||
return from(user).where(user.lastname.eq(lastname)).list(user);
|
||||
}
|
||||
|
||||
long updateLastnamesTo(String lastname);
|
||||
public long updateLastnamesTo(String lastname) {
|
||||
|
||||
return update(user).set(user.lastname, lastname).execute();
|
||||
}
|
||||
|
||||
long deleteAllWithLastname(String lastname);
|
||||
}
|
||||
public long deleteAllWithLastname(String lastname) {
|
||||
|
||||
private static class UserRepositoryImpl extends QueryDslRepositorySupport
|
||||
implements UserRepository {
|
||||
|
||||
private static final QUser user = QUser.user;
|
||||
|
||||
|
||||
public List<User> findUsersByLastname(String lastname) {
|
||||
|
||||
return from(user).where(user.lastname.eq(lastname)).list(user);
|
||||
}
|
||||
|
||||
|
||||
public long updateLastnamesTo(String lastname) {
|
||||
|
||||
return update(user).set(user.lastname, lastname).execute();
|
||||
}
|
||||
|
||||
|
||||
public long deleteAllWithLastname(String lastname) {
|
||||
|
||||
return delete(user).where(user.lastname.eq(lastname)).execute();
|
||||
}
|
||||
}
|
||||
return delete(user).where(user.lastname.eq(lastname)).execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,123 +31,103 @@ import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionException;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test for transactional behaviour of repository operations.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@ContextConfiguration({ "classpath:config/namespace-autoconfig-context.xml",
|
||||
"classpath:tx-manager.xml" })
|
||||
public class TransactionalRepositoryTests extends
|
||||
AbstractJUnit4SpringContextTests {
|
||||
@ContextConfiguration({ "classpath:config/namespace-autoconfig-context.xml", "classpath:tx-manager.xml" })
|
||||
public class TransactionalRepositoryTests extends AbstractJUnit4SpringContextTests {
|
||||
|
||||
@Autowired
|
||||
UserRepository repository;
|
||||
@Autowired
|
||||
UserRepository repository;
|
||||
|
||||
@Autowired
|
||||
DelegatingTransactionManager transactionManager;
|
||||
@Autowired
|
||||
DelegatingTransactionManager transactionManager;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
transactionManager.resetCount();
|
||||
}
|
||||
|
||||
transactionManager.resetCount();
|
||||
}
|
||||
@After
|
||||
public void tearDown() {
|
||||
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
@Test
|
||||
public void simpleManipulatingOperation() throws Exception {
|
||||
|
||||
repository.deleteAll();
|
||||
}
|
||||
repository.saveAndFlush(new User("foo", "bar", "foo@bar.de"));
|
||||
assertThat(transactionManager.getTransactionRequests(), is(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unannotatedFinder() throws Exception {
|
||||
|
||||
@Test
|
||||
public void simpleManipulatingOperation() throws Exception {
|
||||
repository.findByEmailAddress("foo@bar.de");
|
||||
assertThat(transactionManager.getTransactionRequests(), is(0));
|
||||
}
|
||||
|
||||
repository.saveAndFlush(new User("foo", "bar", "foo@bar.de"));
|
||||
assertThat(transactionManager.getTransactionRequests(), is(1));
|
||||
}
|
||||
@Test
|
||||
public void invokeTransactionalFinder() throws Exception {
|
||||
|
||||
repository.findByAnnotatedQuery("foo@bar.de");
|
||||
assertThat(transactionManager.getTransactionRequests(), is(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unannotatedFinder() throws Exception {
|
||||
@Test
|
||||
public void invokeRedeclaredMethod() throws Exception {
|
||||
|
||||
repository.findByEmailAddress("foo@bar.de");
|
||||
assertThat(transactionManager.getTransactionRequests(), is(0));
|
||||
}
|
||||
repository.findOne(1);
|
||||
assertFalse(transactionManager.getDefinition().isReadOnly());
|
||||
}
|
||||
|
||||
public static class DelegatingTransactionManager implements PlatformTransactionManager {
|
||||
|
||||
@Test
|
||||
public void invokeTransactionalFinder() throws Exception {
|
||||
private PlatformTransactionManager txManager;
|
||||
private int transactionRequests;
|
||||
private TransactionDefinition definition;
|
||||
|
||||
repository.findByAnnotatedQuery("foo@bar.de");
|
||||
assertThat(transactionManager.getTransactionRequests(), is(1));
|
||||
}
|
||||
public DelegatingTransactionManager(PlatformTransactionManager txManager) {
|
||||
|
||||
this.txManager = txManager;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokeRedeclaredMethod() throws Exception {
|
||||
public void commit(TransactionStatus status) throws TransactionException {
|
||||
|
||||
repository.findOne(1);
|
||||
assertFalse(transactionManager.getDefinition().isReadOnly());
|
||||
}
|
||||
txManager.commit(status);
|
||||
}
|
||||
|
||||
public static class DelegatingTransactionManager implements
|
||||
PlatformTransactionManager {
|
||||
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
|
||||
|
||||
private PlatformTransactionManager txManager;
|
||||
private int transactionRequests;
|
||||
private TransactionDefinition definition;
|
||||
this.transactionRequests++;
|
||||
this.definition = definition;
|
||||
|
||||
return txManager.getTransaction(definition);
|
||||
}
|
||||
|
||||
public DelegatingTransactionManager(PlatformTransactionManager txManager) {
|
||||
public int getTransactionRequests() {
|
||||
|
||||
this.txManager = txManager;
|
||||
}
|
||||
return transactionRequests;
|
||||
}
|
||||
|
||||
public TransactionDefinition getDefinition() {
|
||||
|
||||
public void commit(TransactionStatus status)
|
||||
throws TransactionException {
|
||||
return definition;
|
||||
}
|
||||
|
||||
txManager.commit(status);
|
||||
}
|
||||
public void resetCount() {
|
||||
|
||||
this.transactionRequests = 0;
|
||||
this.definition = null;
|
||||
}
|
||||
|
||||
public TransactionStatus getTransaction(TransactionDefinition definition)
|
||||
throws TransactionException {
|
||||
public void rollback(TransactionStatus status) throws TransactionException {
|
||||
|
||||
this.transactionRequests++;
|
||||
this.definition = definition;
|
||||
|
||||
return txManager.getTransaction(definition);
|
||||
}
|
||||
|
||||
|
||||
public int getTransactionRequests() {
|
||||
|
||||
return transactionRequests;
|
||||
}
|
||||
|
||||
|
||||
public TransactionDefinition getDefinition() {
|
||||
|
||||
return definition;
|
||||
}
|
||||
|
||||
|
||||
public void resetCount() {
|
||||
|
||||
this.transactionRequests = 0;
|
||||
this.definition = null;
|
||||
}
|
||||
|
||||
|
||||
public void rollback(TransactionStatus status)
|
||||
throws TransactionException {
|
||||
|
||||
txManager.rollback(status);
|
||||
}
|
||||
}
|
||||
txManager.rollback(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link MergingPersistenceUnitManager}.
|
||||
*
|
||||
@@ -38,22 +37,20 @@ import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MergingPersistenceUnitManagerUnitTests {
|
||||
|
||||
@Mock
|
||||
PersistenceUnitInfo oldInfo;
|
||||
@Mock
|
||||
PersistenceUnitInfo oldInfo;
|
||||
|
||||
@Mock
|
||||
MutablePersistenceUnitInfo newInfo;
|
||||
@Mock
|
||||
MutablePersistenceUnitInfo newInfo;
|
||||
|
||||
@Test
|
||||
public void addsUrlFromOldPUItoNewOne() throws MalformedURLException {
|
||||
|
||||
@Test
|
||||
public void addsUrlFromOldPUItoNewOne() throws MalformedURLException {
|
||||
MergingPersistenceUnitManager manager = new MergingPersistenceUnitManager();
|
||||
URL jarFileUrl = new URL("file:foo/bar");
|
||||
|
||||
MergingPersistenceUnitManager manager =
|
||||
new MergingPersistenceUnitManager();
|
||||
URL jarFileUrl = new URL("file:foo/bar");
|
||||
|
||||
when(oldInfo.getJarFileUrls()).thenReturn(Arrays.asList(jarFileUrl));
|
||||
manager.postProcessPersistenceUnitInfo(newInfo, oldInfo);
|
||||
verify(newInfo).addJarFileUrl(jarFileUrl);
|
||||
}
|
||||
when(oldInfo.getJarFileUrls()).thenReturn(Arrays.asList(jarFileUrl));
|
||||
manager.postProcessPersistenceUnitInfo(newInfo, oldInfo);
|
||||
verify(newInfo).addJarFileUrl(jarFileUrl);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user