如何从spring boot jpa中的两个表中获取数据

时间:2017-01-31 18:44:49

标签: java spring spring-boot jpa spring-data-jpa

我有user_infotopics表,如下所示:

带有列的

user_info表:

id, username, userImage, token, role

包含列的主题表:

id, topicId, title, details, dayPosted, username, userImage

在用户登录时,我希望从topics表中获取role表和user_role的信息。

目前我正在获取这样的数据,但这不包括角色信息。

@RequestMapping(path = "/get_data_on_login", method = RequestMethod.GET)
    public ResponseEntity get_data_on_login(@RequestParam(value="username") String username) throws Exception {
        List<TopicBean> topicBean = topicService.findAllTopics();
        return new ResponseEntity(topicBean, HttpStatus.OK);
    }

我如何从user_role表中同时使用角色以及上述数据?

1 个答案:

答案 0 :(得分:2)

像以下一样出了什么问题:

@RequestMapping(path = "/get_data_on_login", method = RequestMethod.GET)
public ResponseEntity get_data_on_login(
       @RequestParam(value="username") String userName) throws Exception {
  List<TopicBean> topics = topicService.findAllTopics( userName );
  List<UserRoleBean> roles = roleService.findAllRoles( userName );
  return new ResponseEntity( new LoginData( topics, roles ), HttpStatus.OK );
}

您的LoginData课程将是:

public class LoginData {
   private final List<TopicBean> topics;
   private final List<UserRoleBean> roles;

   public LoginData(List<TopicBean> topics, List<UserRoleBean> roles) {
     this.topics = topics;
     this.roles = roles;
   }

   public List<TopicBean> getTopics() { return topics; }
   public List<UserRoleBean> getRoles() { return roles; }   }
}

你会得到一个类似的JSON响应:

{ "topics": [{topic1},{topic2}], "roles": [{role1},{role2}] }