Home > Software engineering >  I want to get info only filtering by username
I want to get info only filtering by username

Time:09-30

I want to get results that I filtering by "username"

This is my Controller

import java.util.List;

@RequestMapping("/post")
@RestController
@RequiredArgsConstructor
public class PostController {

    private final PostService postService;

    @GetMapping("/data")
    public ResponseEntity<List<Posts>>findPost(PostSearch username) {
        return new ResponseEntity<>(postService.findPosts(username), HttpStatus.OK);
    }
}

This is Service.class

@Service
@Transactional
@RequiredArgsConstructor
public class PostService {

    private final PostsRepository postsRepository;



    public List<Posts> findPosts(PostSearch postSearch){
        return postsRepository.findAllByUsername(postSearch);

This is PostSearch.class

@Getter
@Setter
public class PostSearch {

    private String username;
}

This is PostsRepository.class

@Repository
public class PostsRepository {

    private final EntityManager em;

    public PostsRepository(EntityManager em) {
        this.em = em;
    }

    public void save(Posts posts){
        em.persist(posts);
    }

    public List<Posts> findAllByUsername(PostSearch postSearch){
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Posts> cq = cb.createQuery(Posts.class);
        Root<Posts> o = cq.from(Posts.class);
        Join<Object,Object> m = o.join("member", JoinType.INNER); //posts의 속성 member

        List<Predicate> criteria = new ArrayList<>();

        //username으로 post 검색
        if (StringUtils.hasText(postSearch.getUsername())) {
            Predicate username = cb.equal(m.get("username"),postSearch.getUsername());
                    //cb.like(m.<String>get("username"), "%"   postSearch.getUsername()   "%"); //member.username
            criteria.add(username);
        }

        cq.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
        TypedQuery<Posts> query = em.createQuery(cq).setMaxResults(1000);
        return query.getResultList();
    }
}

In my DB(MySQL), Posts Table has data like this

enter image description here

When I send GetMethod through PostMan, It takes all data from DB like this

enter image description here

I just want to "userA" info As JsonType but it takes all of users.

I don't know the reason....

CodePudding user response:

You shouldn't use a body with get. Here's the reason why: HTTP GET with request body

But in your code there is missing an annotation @RequestBody

public ResponseEntity<List<Posts>>findPost(@RequestBody PostSearch username) 

Without this annotation the body will not be set to the username parameter.

Please find more information here: https://www.baeldung.com/spring-request-response-body

  • Related