Last active
May 31, 2020 11:41
-
-
Save cupjoo/a7a52d8fe94936546489577b88381b50 to your computer and use it in GitHub Desktop.
ManyToMany
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
@Entity | |
public class Account { | |
// ... | |
@OneToMany(mappedBy = "account") | |
private List<AccountTag> accountTags = new ArrayList<>(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
@RequiredArgsConstructor | |
@Transactional | |
@Service | |
public class AccountService { | |
private final AccountRepository accountRepository; | |
private final TagRepository tagRepository; | |
private final AccountTagRepository accountTagRepository; | |
public void addTag(Account account, String tagTitle) { | |
Tag tag = tagRepository.findByTitle(tagTitle) | |
.orElse(tagRepository.save(Tag.builder().title(tagTitle).build())); | |
Account byId = accountRepository.findById(account.getId()) | |
.orElseThrow(() -> new UsernameNotFoundException(account.getNickname())); | |
accountTagRepository.save(AccountTag.builder() | |
.account(byId).tag(tag).build()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
@Entity | |
public class AccountTag { | |
@Id @GeneratedValue | |
private Long id; | |
@ManyToOne | |
@JoinColumn(name = "account_id") | |
private Account account; | |
@ManyToOne | |
@JoinColumn(name = "tag_id") | |
private Tag tag; | |
@Builder | |
public AccountTag(Account account, Tag tag){ | |
this.account = account; | |
this.tag = tag; | |
addTag(); | |
} | |
private void addTag(){ | |
account.getAccountTags().add(this); | |
tag.getAccountTags().add(this); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
@Entity | |
public class Tag { | |
// ... | |
@OneToMany(mappedBy = "tag") | |
private List<AccountTag> accountTags = new ArrayList<>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment