【问题标题】:Spring Repository Custom Query Spel Evaluation Always NullSpring Repository 自定义查询拼写评估始终为空
【发布时间】:2016-04-17 08:09:20
【问题描述】:

每次我在存储库中调用 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
    );
}

【问题讨论】:

    标签: spring jpa spring-data spring-data-jpa


    【解决方案1】:

    只需将 %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
    );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-23
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      相关资源
      最近更新 更多