【发布时间】:2018-11-23 02:16:50
【问题描述】:
我正在学习如何使用 Spring JPA,并且我已经配置了我的数据库以成功地将元素添加到我的数据库中。我只是无法制定一个查询来检索我的结果(员工列表,按姓氏过滤):
//员工实体:
@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
long id;
String firstName;
String lastName;
public Employee() { }
public Employee(long id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id != other.id)
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
我的问题在于下面我的存储库界面中的查询。调用findByLastName(String lastName) 方法时,我总是收到一个空集合——即使传递了我知道数据库中存在的姓氏:
public interface EmployeeRepository
extends CrudRepository<Employee, Long> {
@Query("select u from Employee u where u.lastName = ?1")
public Collection<Employee> findByLastName(String lastName);
}
还值得一提的是,我正在查询的列在我的数据库列中被命名为last_name(带有下划线)。我不确定这是否有什么不同。
我哪里做错了?
【问题讨论】: