简体   繁体   中英

Spring data JPA: find by column of custom class type's member

I have an entity Person which has a property Name. Name is not marked as entity. For the Name class I have an AttributeConverter which creates a full name by string concatenation of first and last name. So for the person entity the column name is of type String.

@Entity
public class Person {
    // ...  
@Convert(converter = NameAttributeConverter.class)
@Column

private Name name;
    // ...
}

public final class Name implements Comparable, Serializable {
      // ...
      private String firstName;
      private String lastName;
      // ...
}

This works. But now I want to extend my person repository. I want to find persons by her lastName. But

List<Person> findByName_LastName(String lastName);

or

List<Person> findByNameLastName(String lastName);

does not work. I get the following exception:

PersonRepository.findByName_LastName(java.lang.String)! Illegal attempt to dereference path source [null.name] of basic type

How can I solve the problem? Thanks and regards

EDIT:

public interface PersonRepository extends CrudRepository<Person, Long>{
    // The repository works without the findByName...
    // List<Person> findByName_LastName(String lastName);
}

This doesn't work with query derivation and it can't work because in general and in your case the function applied by the conversion is not reversible. This means in order for Spring Data to implement this it would need to analyse the conversion, invert it, ie create a set of functions that produce the first name and last name from the concatenated String stored in the database, and implement it using the Criteria API. I think it is obvious this can't be done.

If you know what query should be executed use a @Query annotation.

The better solution would be to store the lastname in a separate column so it can easily be accessed.

If

You treat firstname and lastname as a column in database since you use Attribute converter for name column. So JPA treats name as a column of type Name and can't do query on Name object type field. The better solution is to store firstname and lastname in a separate column so that you can query easily. But if you want make a field concat of firstname and lastname and query on concat field also then you can use @Formula()

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Formula(value = "CONCAT(last_name, first_name)")
private String name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM