Spring数据JPA:按列查找自定义类类型的成员 [英] Spring data JPA: find by column of custom class type's member
问题描述
我有一个实体Person,其属性为Name.名称未标记为实体.对于Name类,我有一个AttributeConverter,它通过姓和名的字符串连接来创建全名.因此,对于人员实体,列名称的类型为字符串.
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);
或
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
public interface PersonRepository extends CrudRepository<Person, Long>{
// The repository works without the findByName...
// List<Person> findByName_LastName(String lastName);
}
推荐答案
您将名字和姓氏视为数据库中的一列,因为您对 name
列使用了属性转换器.因此,JPA将 name
视为类型为 Name
的列,并且无法在 Name
对象类型字段上进行查询.更好的解决方案是将名字和姓氏存储在单独的列中,以便您轻松查询.但是,如果您想创建一个姓和名的字段连续查询并查询连续字段,则可以使用 @Formula()
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;
这篇关于Spring数据JPA:按列查找自定义类类型的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!