[JPA] JAVA Hibernate ORM 하이버네이트란?

반응형

Hibernate는 Java환경을 위한 객체/관계형 매핑솔루션 이며 Hibernate는 자바 클래스에서 데이터베이스를 테이블로 매핑을 처리할 뿐만 아니라 데이터쿼리 검색기능도 제공한다 SQL 및 JDBC에서 수동으로 데이터 처리에 소요되는 시간도 단축할수 있게된다. 간단하게 쿼리를 쓰지 않고 관계형 테이블을 자바 객체로 맵핑을 시켜 사용한다는 것이다.

 

 

유저DTO 생성할때 들어가는 정보는 아래와 같다.

@ 어노테이션을 사용하기 위해서는 Lombok이라는 라이브러리를 사용했다. 해당 어노테이션들은 파라미터가 없는 기본 생성자를 생성해주며 모든 필드 값을 파라미터로 받는 생성자를 만들어 줍니다. Get와 Set을 final이나 ToString을 빈을 설정할때 equals또는 hashCode 메소드를 자동으로 생성해주고있다.

@NoArgsConstructor
@AllArgsConstructor
@Data
public class UserDTO 
{
	private int id;						// PK
	private String userId;
	private String userNick;
	private String userUnique;
	private String userFilename;
	private String userImageUrl;
	private Date userCreatedDate;
	private String userState;
	private Date userUpdateDate;
    
    public UserDTO(final UserEntity entity) {
		this.id = entity.getId();
		this.userId = entity.getUserId();
		this.userNick = entity.getUserNick();
		this.userUnique = entity.getUserUnique();
		this.userFilename = entity.getUserFilename();
		this.userImageUrl = entity.getUserImageUrl();
		this.userCreatedDate = entity.getUserCreatedDate();
		this.userState = entity.getUserState();
		this.userUpdateDate = entity.getUserUpdateDate();
	}
    
    
    public static UserEntity toEntity(final UserDTO dto) {
		return UserEntity.builder()
				.id(dto.getId())
				.userId(dto.getUserId())
				.userNick(dto.getUserNick())
				.userUnique(dto.getUserUnique())
				.userFilename(dto.getUserFilename())
				.userImageUrl(dto.getUserImageUrl())
				.userCreatedDate(dto.getUserCreatedDate())
				.userState(dto.getUserState())
				.userUpdateDate(dto.getUserUpdateDate())
				.build();
	}
}

 

유저테이블을 생성할때 들어가는 정보는 아래와 같다.

@Entity를 사용했으며 id를  Primary key로 지정하며 OneToMany로 1대 다 관계를 형성한다.

 

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;				// Pk
    @Column(unique = true)
    private String userId;
    @Column(unique = true)
    private String userNick;
    private String userUnique;
    private String userFilename;
    private String userImageUrl;
    private Date userCreatedDate;
    private String userState;
    private Date userUpdateDate;

    @OneToMany(fetch = FetchType.LAZY)
    @NotFound(action= NotFoundAction.IGNORE)
    @JoinColumn(name = "user_point_count_id")
    private UserPointCount userPointCount;

    public void setPointCount(UserPointCount userPointCount) {
        this.userPointCount = userPointCount;
        userPointCount.updateUser(this);
    }
}

 

외부 I/O 처리를 위해 @Repository 를 생성.

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Integer> {

    @EntityGraph(attributePaths = {"userPointCount"})
    List<UserEntity> findByUserId(String userId);
}

 

 

 

 

이외에 @Service , @RestController 추가로 생성해 실제 API를 붙여 볼수있고 아래 코드는 간단한 예시.

@Slf4j
@Service
public class UserService {

	@Autowired
    private UserRepository userRepository;
    
      public UserEntity createUser(final UserEntity entity) {
        validateUser(entity);

        userRepository.save(entity);
        log.info("Entity Id : {} is saved.", entity.getId());
        return userRepository.findById(entity.getId()).get();
    }
    
    private void validateUser(final UserEntity entity) {
        if(entity == null) {
            log.warn("Entity cannot be null.");
            throw new RuntimeException("Entity cannot be null.");
        }

        if(entity.getUserId() == null) {
            log.warn("Unknown user.");
            throw new RuntimeException("Unknown user.");
        }
    }
    
}


//------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------

@RestController
public class UserController {
	
    @Autowired
    private UserService userService;
    
    
    @PostMapping("/user/addUser")
    public ResponseEntity<?> addUser(@RequestBody UserDTO dto, 
    	@RequestParam("instance") MultipartFile multipartFile) {
        UserEntity entity = UserDTO.toEntity(dto);
        entity.setId(0);
        UserEntity newUser = userService.createUser(entity);
        UserDTO newDto = new UserDTO(newUser);
        ResponseDTO<UserDTO> response = ResponseDTO.<UserDTO>builder().payload(newDto).build();
        return ResponseEntity.ok().body(response);
        
    }
    

    
}

 

 

반응형