You are on page 1of 1

package com.obdksoft.SData.

services;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import com.obdksoft.SData.Entities.Roles;
import com.obdksoft.SData.Entities.TableUser;
import com.obdksoft.SData.Entities.TableUserInRole;
import com.obdksoft.SData.repositories.RolesRepository;
import com.obdksoft.SData.repositories.UserInRoleRepository;
import com.obdksoft.SData.repositories.UserRepository;

@Service
public class UserInRolService {

@Autowired
private UserInRoleRepository userInRoleRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private RolesRepository roleRepository;

public TableUserInRole createUserInRol(Integer userId, Integer roleId) {


// TODO Auto-generated method stub

Optional<TableUser> resultUser = userRepository.findById(userId);


Optional<Roles> resultRole = roleRepository.findById(roleId);
if (resultUser.isPresent()&&resultRole.isPresent()){

TableUserInRole tableUserInRol=new TableUserInRole();


tableUserInRol.setTableuser(resultUser.get());
tableUserInRol.setRoles(resultRole.get());
return userInRoleRepository.save(tableUserInRol);

}else {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("User %d not found", userId));
}
}
public List<TableUser> findByRoleId(Integer roleId) {
return
userInRoleRepository.findByRoleIdReturnsUserList(roleId).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("Role %d not found", roleId)));
}
public List<TableUser> findByRoleName(String rolName) {
return userInRoleRepository.findByRolesname(rolName).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("Role %s not found", rolName)));
}

You might also like