Spring Data JPA - Convertor

목차

BooleanToYNConverter

Boolean 으로 저장 되는 값을 True, false 로 변경해 값을 저장하기 위한 Convertor

@Converter
public class BooleanToYNConverter implements AttributeConverter<Boolean, String> {
@Override
public String convertToDatabaseColumn(Boolean attribute){
return (attribute != null && attribute) ? "Y" : "N";
}

@Override
public Boolean convertToEntityAttribute(String dbData){
return "Y".equals(dbData);
}
}
@Entity
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class Post extends BaseEntity{

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;

@Column(name = "POST_TITLE", length = 100, nullable = false)
private String title;

@Column(name = "POST_SUBTITLE")
private String subTitle;

@Lob
private String content;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false, referencedColumnName = "username")
@CreatedBy
private UserInfo author;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CATEGORY", nullable = true, referencedColumnName = "CATEGORY_NAME")
private Category category;

@Column(name = "isDeleted")
@ColumnDefault("false")
@Convert(converter = BooleanToYNConverter.class)
private boolean isDeleted;

// ==== 연관관계 편의 메서드 ==== //
public void changeCategory(Category category){
this.category = category;
// 새로운 카테고리에 해당 포스트 추가
category.getPosts().add(this);
}

public void setAuthor(UserInfo author){
this.author = author;
author.getPosts().add(this);
}

public Post updatePost(Post post) {
this.title = post.title;
this.subTitle = post.subTitle;
this.content = post.content;
changeCategory(post.getCategory());
return this;
}
}
Share