Spring data jpa 自定义查询返回,用FastJson把Map转换为JavaBean

@Query("select new map(u.userName as userName , m.plan  as plan ) from User u , MorningReport m where u.id = '1' and  m.id = 1 ")
public Map<String,String> testMap();
@Data
public class UserMorningReport {
    private String userName;
    private String plan;
}
@Slf4j
public class CommentTest extends WorkTileApplicationTests{

    @Autowired
    private UserDao userdao;

    @Test
    public void  testUser(){

        //自定义查询用 
        Map<String, String> testMap = userdao.testMap();
        String itemJSONObj = JSON.toJSONString(testMap);
        System.out.println("itemJSONObj=="+itemJSONObj);
        UserMorningReport group = JSON.parseObject(itemJSONObj, UserMorningReport.class); 
        System.out.println(group.getPlan());
        System.out.println(group.getUserName());
        log.info("group={}", group);
    }
}

与select new map相似的还有select new list、select new set。只研究了此一个,没有研究别的,但大致原理应该是差不多的。

参考—– Hibernate调优之select new map()
http://blog.csdn.net/z69183787/article/details/41362093

猜你喜欢

转载自blog.csdn.net/dgutliangxuan/article/details/78782170