每次我在存储库中调用findByFirstNameContainingOrLastNameContaining函数时,我都会得到错误:
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'firstName' cannot be found on null
我的问题错了吗?我完全不知道错误
这是我的文件:
Person.java
package com.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id;
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
PersonRepository.java
package com.repositories;
import com.model.Person;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface PersonRepository extends CrudRepository<Person, Long> {
@Query("SELECT p FROM Person p WHERE p.firstName LIKE %:firstName% OR "
+ "p.firstName LIKE %:lastName% OR "
+ "p.lastName LIKE %:lastName% OR "
+ "p.lastName LIKE %:firstName%")
public List<Person> findByFirstNameContainingOrLastNameContaining(
@Param(value = "firstName") String firstName,
@Param(value = "lastName") String lastName
);
}
将%xxx%只替换为:{parameter},它就可以工作了。
package com.example.repository;
import com.example.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
@Query("SELECT e FROM Employee e WHERE e.firstName LIKE :firstName OR "
+ "e.firstName LIKE :lastName OR "
+ "e.lastName LIKE :lastName OR "
+ "e.lastName LIKE :firstName")
List<Employee> findByFirstNameContainingOrLastNameContaining(
@Param(value = "firstName") String firstName,
@Param(value = "lastName") String lastName
);
}