首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何向“/user”发出GET请求?<若干查询-这里>,然后在JSON数组中返回所有满足查询条件的用户

如何向“/user”发出GET请求?<若干查询-这里>,然后在JSON数组中返回所有满足查询条件的用户
EN

Stack Overflow用户
提问于 2021-12-06 04:50:18
回答 5查看 430关注 0票数 3

长时间的读者,第一次海报。

我需要帮助。我无法计算出DataBase参数↔。

情况:我把.//?角色=管理&标题=放在邮递员中

期望:是所有管理人员和管理员的用户的混合体。

实战:我的电脑爆炸了。

代码语言:javascript
复制
@RestController
@RequestMapping(path = USERS_PATH)
@Log4j2
public class UserController
// other code...
  @GetMapping
  public ResponseEntity<List<User>>  getUserQuery(
      @RequestParam( required = false, name = "name") String name,
      @RequestParam( required = false, name = "title") String title,
      @RequestParam( required = false, name = "roles") String roles,
      @RequestParam( required = false, name = "email") String email,
      @RequestParam( required = false, name = "password") String password
  ) {
    log.info("Request received for getUserQuery");
    return new ResponseEntity<>(userService.doSomething???(), HttpStatus.OK); // stuff I don't understand yet)
  }

我的问题:在控制器之后,UserService和UserRepository有什么?

额外信息:,我正在使用Spring和H2,但可能需要稍后切换到PostgreSQL DB。

我有下面的代码作为一个独特的电子邮件检查期间放置和张贴在服务层,但我无法得到类似的工作为这个问题。

代码语言:javascript
复制
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("SELECT u FROM User u WHERE u.email = ?1")
  Optional<User> findUserByEmail(String email);
}

咆哮:,这似乎是一件非常普通的事情,我应该已经知道如何这样做了。我不知道。我已经在网上读了大约5个小时了。还是没有回答。我学习了有关规范、Querydsl、@ModelAtribute、DAO和映射RequestParams的内容。然而,我无法找到如何连接这些点。于是,我开始尝试用StringBuilder和一堆逻辑制作一个@Query参数.我开始旋转了。

无论如何,我想避免规格& Querydsl。只需使用@Query和JPA,但更重要的是,我需要一个干净的解决方案/最佳实践。

EN

回答 5

Stack Overflow用户

发布于 2021-12-06 05:39:35

这是一个工作剪。我认为您的存储库存在问题。您正在使用@Query和对查询的开箱即用支持。

服务和存储库中的内容:存储库层(Repo)类用于抽象与DB的交互。

服务层与回购层交互,并对存储库层返回的数据进行按摩。

UserEntity

代码语言:javascript
复制
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;

@Getter
@Setter
@Entity
@Table(name = "users")
@NoArgsConstructor
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "designation")
    private String designation;

    @Column(name = "email")
    private String email;



}

UserRepository

代码语言:javascript
复制
import com.example.code.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {

    Optional<UserEntity> findByName(String name);

    List<UserEntity> findByDesignation(String designation);

    Optional<UserEntity> findByEmail(String email);
}

UserService

代码语言:javascript
复制
import java.util.Collection;

public interface UserService {
    void createUser(UserDTO userDTO);

    Collection<UserDTO> getUsers(
            String username,
            String designation,
            String email
    );
}

UserServiceImpl

代码语言:javascript
复制
import com.example.code.dto.UserDTO;
import com.example.code.entity.UserEntity;
import com.example.code.mapper.UserMapper;
import com.example.code.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public void createUser(UserDTO userDTO) {
        UserEntity userEntity = new UserEntity();
        userEntity.setName(userDTO.getName());
        userEntity.setDesignation(userDTO.getDesignation());
        userEntity.setEmail(userDTO.getEmail());
        userRepository.save(userEntity);
    }

    @Override
    public Collection<UserDTO> getUsers(String username, String designation, String email) {
        Set<UserDTO> userDTOS = new HashSet<>();
        if( !username.isBlank() && !username.isEmpty() && userRepository.findByName(username).isPresent() ) {
            userDTOS.add(UserMapper.toDto(
                    userRepository.findByName(username).get()
            ));
        }
        if(!designation.isBlank() && !designation.isEmpty()) {
            userDTOS.addAll(
                    userRepository.findByDesignation(designation)
                            .stream()
                            .map(UserMapper::toDto)
                            .collect(Collectors.toSet())
            );
        }

        if( !email.isBlank() &&
                !email.isEmpty() &&
                userRepository.findByEmail(email).isPresent() ) {
            userDTOS.add(UserMapper.toDto(
                    userRepository.findByEmail(email).get()
            ));
        }

        return userDTOS;
    }
}

UserMapper

代码语言:javascript
复制
import com.example.code.dto.UserDTO;
import com.example.code.entity.UserEntity;

public class UserMapper {

    public static UserDTO toDto(UserEntity entity) {
        UserDTO userDTO = new UserDTO();
        userDTO.setName(entity.getName());
        userDTO.setDesignation(entity.getDesignation());
        userDTO.setEmail(entity.getEmail());
        return userDTO;
    }
}

TestController

代码语言:javascript
复制
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {

    private final UserService userService;

    @PostMapping
    public ResponseEntity<String> createUser(@RequestBody final UserDTO userDTO) {
        try {
            userService.createUser(userDTO);
        }catch (Exception e) {
            return ResponseEntity.internalServerError().body("Failure");
        }
        return ResponseEntity.ok("Success");
    }

    @GetMapping
    public ResponseEntity<Collection<UserDTO>> getUsers(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "designation", required = false) String designation,
            @RequestParam(value = "email", required = false) String email
    ) {
        return ResponseEntity.ok(userService.getUsers(name, designation, email));
    }
}
票数 2
EN

Stack Overflow用户

发布于 2021-12-06 06:25:21

5.1.6按实例查询,我们来吧:

我们不需要任何东西在我们的回购,因为JpaRepository“已经在船上”!

我们的服务应该是:

代码语言:javascript
复制
package com.example;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.ignoreCase;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;


@Service
public class PersonService {
    @Autowired
    JpaRepository<Person, Long> personRepository;

    public List<Person> find(String name, String title, String roles, String email, String password) {
        Person person = Person.of(name, title, roles, email, password);
        ExampleMatcher matcher = ExampleMatcher
                .matchingAny()
                .withIgnoreNullValues()
                .withMatcher("name", ignoreCase())
                .withMatcher("title", ignoreCase())
                .withMatcher("roles", ignoreCase())
                .withMatcher("email", ignoreCase())
                .withMatcher("password", exact());
        return personRepository.findAll(Example.of(person, matcher));
    }
} // UN-TESTED, but compilable ;)

...but我们看到:仅用这五个参数就可以进行多少“调整”。

用法

..。 示例查询非常适合于几个用例:

  • 使用一组静态或动态约束查询数据存储。
  • 频繁地重构域对象,而不必担心中断现有的查询。
  • 独立于底层数据存储API工作。

示例查询也有几个限制:

  • 不支持嵌套或分组属性约束,如firstname = ?0 or (firstname = ?1 and lastname = ?2)
  • 只支持字符串的开始/包含/结束/regex匹配,以及其他属性类型的精确匹配。
票数 1
EN

Stack Overflow用户

发布于 2021-12-06 07:10:26

SQL ANDOR子句的组合应该符合您的目的。下面使用服务和存储库类给出了一个示例。

UserService

代码语言:javascript
复制
    public List<User> doingSomething(String name, String title, String roles, String email,String password) {
        return userRepository.detailQuery(name, title, roles, email,  password);
    }

UserRepository

代码语言:javascript
复制
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @Query("SELECT u FROM User u WHERE (:name is null or u.name = :name) and (:title is null or u.title = :title) and (:roles is null or u.roles = :roles) and (:email is null or u.email = :email) and (:password is null or u.password = :password)")
    List<User> detailQuery(@Param("name") String name,
                           @Param("title") String title,
                           @Param("roles") String roles,
                           @Param("email") String email,
                           @Param("password") String password);

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70241010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档