我正在 mvc spring 中执行搜索功能。我想搜索名字和姓氏。如果我在搜索框中输入一个字符串并按回车键,如果在姓氏中没有找到它,我将在名字中进行搜索,反之亦然。这意味着我想输入一个字符串并搜索所有字段。这是我的节目内容。
员工:
@Entity
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int 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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
存储库:
@Repository
public interface EmployeeDAO extends JpaRepository<Employee,Integer>{
List<Employee> findEmployeeByFirstNameOrLastName(String searchName);
}
Controller :
@RequestMapping(value = "/search")
public ModelAndView searchByFirstName(@RequestParam String searchName) {
ModelAndView view = new ModelAndView("showEmployee");
return view;
}
查看:
<div class="row">
<form method="get" action="/search">
<div class="small-3 columns">
<input type="text" id ="txt" name="searchName" >
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search</button>
</div>
</form>
</div>
我已经运行,但它不能同时搜索名字或姓氏。两个人如何使用一个参数搜索名字或姓氏
最佳答案
您需要提供两个字段:
List<Employee> findEmployeeByFirstNameOrLastName(String firstName, String lastName);
然后调用它:
findEmployeeByFirstNameOrLastName("searchName", "searchName");
获取firstName
或lastName
等于“searchName”
的Employee
最终代码如下:
@Repository
public interface EmployeeDAO extends JpaRepository<Employee,Integer>{
List<Employee> findEmployeeByFirstNameOrLastName(String firstName, String lastName);
}
@RequestMapping(value = "/search")
public ModelAndView searchByFirstName(@RequestParam String searchName) {
ModelAndView view = new ModelAndView("showEmployee");
// Access employeeDAO here, or use employeeService if you using service
List<Employee> employees = employeeDao.findEmployeeByFirstNameOrLastName(searchName, searchName);
view.addObject("employees", employees);
return view;
}
对于更复杂的情况,您可能需要查看 JPA Criteria API 或 QueryDsl 来创建条件组合,而不是像上面那样提供两个字段 firstName
、lastName
关于spring - 如何使用条件或 spring jpa 进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774104/