kittu
kittu

Reputation: 7008

How do I get data from two tables in spring boot jpa

I have user_info and topics table like this:

user_info table with columns:

id, username, userImage, token, role

topics table with columns:

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

On user login, I would like to get information from topics table and role from user_role table.

For now I am getting the data like this, but this doesn't include role information.

@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);
    }

How do I user role as well from user_role table along with above data?

Upvotes: 0

Views: 6079

Answers (1)

Naros
Naros

Reputation: 21103

What's wrong with something like:

@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 );
}

Your LoginData class would be:

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; }   }
}

You would get a JSON response that looked like:

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

Upvotes: 2

Related Questions