@jsonignore
@ToString(exclude = "") ....
RDB 구조
해당 Service
public boolean updateCharacters(Integer id, List<CharacterInfoDto> characters){
// 캐릭터에 매핑할 유저 조회
Optional<User> userOptional = userService.getById(id);
if(!userOptional.isPresent()) {
System.out.println("[Error] No User Error");
return false;
}
List<CharacterInfoDto> originCharacters = getCharacterByUserId(id);
// 갱신할 캐릭터들 List 생성
List<String> addCharNames = new ArrayList<>();
for(CharacterInfoDto dto : characters){
addCharNames.add(dto.getCharName());
}
// 체크되지 않는 캐릭터 삭제
try{
List<Integer> deleteIds = new ArrayList<>();
for(CharacterInfoDto dto : originCharacters){
String originName = dto.getCharName();
if (!addCharNames.contains(originName)) {
deleteIds.add(dto.getId());
}else{
// 기존에 있는 이름은 추가할 배열에서 삭제
addCharNames.remove(originName);
}
}
// 제외된 데이터 삭제 및 예외처리
if(deleteIds.size() > 0) {
characterInfoRepository.deleteAllById(deleteIds);
}else{
// 추가할 데이터가 없으면 알림을 보내고 성공처리
System.out.println("[Alert] No data Changed");
return true;
}
// 추가된 캐릭터들의 Dto를 Entity로 변환
List<CharacterInfo> addCharacters = new ArrayList<>();
for(CharacterInfoDto character : characters){
if(addCharNames.contains(character.getCharName())){
addCharacters.add(CharacterInfo.toEntity(character, userOptional.get()));
}
}
// 추가할 캐릭터를 DB에 추가
if(addCharacters.size() > 0) {
characterInfoRepository.saveAll(addCharacters);
System.out.println("[Alert] Update Success");
return true;
}else{
return false;
}
}catch(Exception e){
System.out.println(String.format("[Error] %s", e));
return false;
}
}
User Entity
package com.example.loa.Entity;
import com.example.loa.Dto.UserDto;
import jakarta.persistence.*;
import lombok.*;
import java.util.ArrayList;
import java.util.List;
@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
// 출력 시에 객체 무한 참조를 막기 위한 exclude
@ToString(exclude = {"characterInfos", "crews", "userCrews", "applies", "boards"})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name="user_id", nullable = false)
private String userId;
private String password;
@Column(name="char_name", nullable = false)
private String charName;
private String server;
@OneToMany(mappedBy = "user")
List<CharacterInfo> characterInfos = new ArrayList<>();
@OneToMany(mappedBy = "user")
List<Crew> crews = new ArrayList<>();
@OneToMany(mappedBy = "user")
List<UserCrew> userCrews = new ArrayList<>();
@OneToMany(mappedBy = "user")
List<Apply> applies = new ArrayList<>();
@OneToMany(mappedBy = "user")
List<Board> boards = new ArrayList<>();
public static User toEntity(UserDto dto) {
return User.builder()
.userId(dto.getUserId())
.password(dto.getPassword())
.charName(dto.getCharName())
.server(dto.getServer())
.build();
}
public void update(String password, String charName, String server){
this.password = password;
this.charName = charName;
this.server = server;
}
}