Spring MVC - 使用Param搜索

时间:2016-04-14 13:30:20

标签: database spring spring-mvc

我想从数据库示例搜索我有三个文本字段 名字,姓氏和性别 如果我在那里输入 一些名字,一些姓氏,男性我想搜索具有该特定名称和性别的所有人并显示它我该如何做? 注意:我刚接触Spring,刚开始学习谢谢

控制器:

  @RequestMapping(value = "/student/search", method = RequestMethod.GET)
  public String searchStudent(@Param("name") String name, @Param("type") String type, Map<String, Object> model) {
    Map<String, String> params = new HashMap<String, String>();
    params.put("name", name);
    params.put("type", gender);
    model.put("students",studentRepository.findAll(StudentSpecification.search(params)));
    return "/students/list";
  }
}

规格:

 public static Specification<Student> search(final Map<String, String> params) {
    return (root, query, criteriaBuilder) -> {
      List<Predicate> predicates = new ArrayList<Predicate>();

      params.forEach((k, v) -> {
        if (StringUtils.equals(k, "name")) {
          if (StringUtils.isNotBlank(v)) {
            Predicate hasFirstName =
                criteriaBuilder.like(root.join("user").<String>get("firstName"), "%" + v + "%");
            Predicate hasLastName =
                criteriaBuilder.like(root.join("user").<String>get("lastName"), "%" + v + "%");
            predicates.add(criteriaBuilder.or(hasFirstName, hasLastName));
          }
        }
      });

      return criteriaBuilder.and(predicates.toArray(new Predicate[] {}));
    };

  }

}

2 个答案:

答案 0 :(得分:2)

我从你的代码中假设你正在使用带有规范的Spring数据jpa,对吧? 如果是这样,你需要生成你的实体的MetaModel,如果你正在使用maven,添加下面的代码,这将为你做这个

     <plugin>
            <groupId>org.bsc.maven</groupId>
            <artifactId>maven-processor-plugin</artifactId>
            <version>2.0.5</version>
            <executions>
                <execution>
                    <id>process</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <phase>generate-sources</phase>
                    <configuration>
                        <processors>
                             <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                        </processors>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-jpamodelgen</artifactId>
                    <version>4.3.6.Final</version>
                </dependency>
            </dependencies>
        </plugin> 

我想你有一个名为Student的实体,这个插件声明会生成一个后缀为'Student _'

的classe

然后你可以实现规范界面,就像这样

 public class StudentSpecification {

    public static Specification<Student> search(final Map<String, String> params) {

        return new Specification<Student>() {
           @Override
           public Predicate toPredicate(Root<Student> studentRoot,   CriteriaQuery<?> query, CriteriaBuilder cb) {
            Predicate res = null;


            if(params.containKey("name"))
            res = cb.equal(studentRoot.get(Student_.name), params.get("name"));

            if(params.containKey("type"))
                if(res ==null)
                    res = cb.equal(studentRoot.get(Student_.name), params.get("type"));
                else
                    res = cb.and(res, cb.equal(studentRoot.get(Student_.name), params.get("type")));

           return res;
        }

    }
}

当然你的StudentRepository类应该扩展JpaSpecificationExecutor,就像这样

interface StudentRepository extends  JpaSpecificationExecutor<Student> {
 }

答案 1 :(得分:0)

您可以使用@Query,在存储库中添加方法来执行此操作:

@Query("SELECT e FROM STUDENT e WHERE e.name = ?1 AND e.type = ?2")
public List<student> findAll(String name, String type);

在控制器中使用该方法:

@RequestMapping(value = "/student/search", method = RequestMethod.GET)
public String searchStudent(@Param("name") String name, @Param("type") String type, Map<String, Object> model) {
       model.put("students",studentRepository.findAll(name, type));
       return "/students/list";
}