JPA : How to convert a native query result set to POJO class collection

后端 未结 21 1464
孤街浪徒
孤街浪徒 2020-11-22 09:23

I am using JPA in my project.

I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.

21条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:52

    All you need is a DTO with a constructor :

    public class User2DTO implements Serializable {
    
        /** pode ser email ou id do Google comecando com G ou F para Facebook */
        private String username;
    
        private String password;
    
        private String email;
    
        private String name;
    
        private Integer loginType;
    
        public User2DTO(Object...fields) {
            super();
            this.username = (String) fields[0];
            this.name = (String) fields[1];
            this.email = (String) fields[2];
            this.password = (String) fields[3];
            this.loginType = (Integer) fields[4];
        }
    

    and call it :

    EntityManager em = repo.getEntityManager();
            Query q = em.createNativeQuery("SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u");
            List objList = q.getResultList();
            List ooBj = objList.stream().map(User2DTO::new).collect(Collectors.toList());
    

提交回复
热议问题