int로 반환 받을때 객체로 반환 받을때의 차이?
- int 반환값과 객체 반환값의 차이점
- 멤버수 조회, 프로젝트 역할 조회 등에서 어떤 방식이 더 나은지
- 순서대로 차례로 설명해달라고 요청
더보기
int 반환값의 특징:
단순한 수치 정보만 반환
null이 될 수 없음 (primitive type)
메모리 효율적
추가 정보가 필요 없는 경우 적합
객체 반환값의 특징:
여러 필드 정보를 포함할 수 있음
null이 될 수 있음 (참조 타입)
더 많은 정보를 담을 수 있음
확장성이 좋음
여기에서 나는 에러
Type mismatch: cannot convert from UserProjectRole to int
public int getUserProjectRole(int projectId, int userId){
int rows= userProjectRoleDao.selectUserProjectRole(projectId, userId);
return rows;
}
현재 문제의 원인이 되는 것은 DAO와 xml 에서 설정한 값이랑 service에서 단순하게 받으려고 int로 주문을 한거랑 불일치한다.
// DAO
// 프로젝트 참여하는 사용자의 플젝 내 역할 조회 selectUserProjectRole
UserProjectRole selectUserProjectRole(@Param("projectId") int projectId, @Param("userId") int userId);
//xml
<!--특정 사용자의 프로젝트 역할 조회 -->
<select id="selectUserProjectRole" parameterType="UserProjectRole" resultType="UserProjectRole">
select uprRole
from userProjectRole
where project_id = #{projectId} AND user_id = #{userId}
</select>
방법1:
resultType을 int로 바꾸고 dao도 userprojectrole로 받지 말고 int로 받게 만들어준다. 이경우 service는 그대로 유지해도 된다.
방법 2:
service에서 객체 역할값을 추출한다.-> int로 바꿀게 아니라 admin인지 memeber인지가 나오므로 string으로 선회한다.
public int getUserProjectRole(int projectId, int userId){
UserProjectRole userProjectRole = userProjectDao.selectUserProjectRole(projectId,userId);
if(userProjectRole !=null){
return userProjectRole.getUprRole();
}
else{
return -1;
}
컨트롤러에서 Map으로 반환 할것인가. List로 반환할것인가 ..?
//프로젝트 멤버 목록 조회
@GetMapping("/list")
public Map<String, Object> userProjectRoleList(@RequestParam("projectId")int projectId){
log.info("list API 호출! projectId:{}",projectId);
List<UserProjectRole> inprojectmember= userProjectRoleService.getUsersProject(projectId);
log.info(inprojectmember.toString());
Map<String,Object> map = new HashMap<>();
map.put("lists", inprojectmember);
log.info(map.toString());
return map;
}
{
"lists": [
{
"uprId": 53,
"userId": 45,
"projectId": 58,
"uprRole": "ADMIN"
},
{
"uprId": 63,
"userId": 44,
"projectId": 58,
"uprRole": "MEMBER"
}
]
}
리스트를 map으로 또 감싸서 리턴해서 굳이 이럴 필요가 있나 싶다..
그냥 list로 변경하고 결과 값을
@GetMapping("/list")
public List<UserProjectRole> userProjectRoleList(@RequestParam("projectId")int projectId){
List<UserProjectRole> projectmemberlist= userProjectRoleService.getUsersProject(projectId);
log.info(projectmemberlist.toString());
return projectmemberlist;
}
[
{
"uprId": 53,
"userId": 45,
"projectId": 58,
"uprRole": "ADMIN"
},
{
"uprId": 63,
"userId": 44,
"projectId": 58,
"uprRole": "MEMBER"
}
]
이렇게 교체해줌
'【Spring】' 카테고리의 다른 글
| [spring AI] .content() 사용이유 (0) | 2025.10.22 |
|---|---|
| [@RequestParam] RequestParam의 순서 (0) | 2025.09.28 |
| [Interceptor] (0) | 2025.09.15 |
| [ORM] mybatis 시작하기 부터 구성요소 (0) | 2025.09.01 |
| [RestAPI] update와 select를 구분하자 (0) | 2025.09.01 |