Suppose I have an embeddable class, that is embedded in an entity class like below.
@Embeddable
public class FullName {
private String firstName;
private String lastName;
// constructor, getters, setters, as needed
}
@Entity
public class Account {
@Embedded
private FullName fullName;
// id, other data and methods
}
One person can have multiple accounts, hence the full name is not a key for the Account class. What I would like to have, is the following method in a jpa repository
public interface AccountRepository extends CrudRepository<Account, Long> {
Collection<Account> findAllByFullName(FullName fullName);
}
Initially, I thought this would just work, but apparently it's not that simple. I could not get a method like this to work. The only thing I thought might help, was implement an equals method on FullName, saying that a FullName with same first and last name are equal, but this had no effect.
What I ended up doing for the moment is this:
public interface AccountRepository extends CrudRepository<Account, Long> {
Collection<Account> findAllByFullNameFirstNameAndFullNameLastName(String firstName, String lastName);
default Collection<Account> findAllByFullName(FullName fullName) {
return findAllByFullNameFirstNameAndFullNameLastName(fullName.getFirstName(), fullName.getLastName());
}
}
Is there a way for me to avoid creating this intermediary (visible) method?
You can use Example as below,
Collection<Account> findAll(Example< Account > account);
And then pass it as,
FullName fullName = new FullName(fname, lname);
Account acc = new Account();
acc.setFullName(fullName);
Collection<Account> accounts = accountRepository.findAll(Example.of(acc));
Hope it helps.