Skip to content

Instantly share code, notes, and snippets.

@cupjoo
Last active May 31, 2020 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cupjoo/a7a52d8fe94936546489577b88381b50 to your computer and use it in GitHub Desktop.
Save cupjoo/a7a52d8fe94936546489577b88381b50 to your computer and use it in GitHub Desktop.
ManyToMany
// ...
@Entity
public class Account {
// ...
@OneToMany(mappedBy = "account")
private List<AccountTag> accountTags = new ArrayList<>();
}
// ...
@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());
}
}
// ...
@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);
}
}
// ...
@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