Непроверенный пример с использованием Hibernate, JPA, Lombok:
Пользовательский объект
@Entity
@Table(name = "USER")
@SequenceGenerator(name = "userSeqId", sequenceName = "user_seq_id", allocationSize = 1)
@NoArgsConstructor
@Setter
@Getter
public class User {
@Id
@GeneratedValue(generator = "userSeqId", strategy = GenerationType.AUTO)
private Long id;
@NotBlank
@Column(name = "EMAIL", unique = true)
private String email;
}
Примечания
@Entity
@Table(name = "NOTES")
@SequenceGenerator(name = "notesSeqId", sequenceName = "notes_seq_id", allocationSize = 1)
@NoArgsConstructor
@Setter
@Getter
public class Notes {
@Id
@GeneratedValue(generator = "notesSeqId", strategy = GenerationType.AUTO)
private Long id;
@NotBlank
@Column(name = "TITLE")
private String title;
@NotBlank
@Column(name = "MESSAGE")
private String message;
}
UserNotes entity
@Entity
@Table(name = "USER_NOTES")
@NoArgsConstructor
@Setter
@Getter
public class UserNotes {
@EmbeddedId
private UserNotesKey id;
@NotNull
@ManyToOne
@MapsId("USER_ID")
@JoinColumn(name = "USER_ID")
@OnDelete(action = OnDeleteAction.CASCADE)
private User user;
@NotNull
@ManyToOne(cascade = CascadeType.PERSIST)
@MapsId("NOTES_ID")
@JoinColumn(name = "NOTES_ID")
@OnDelete(action = OnDeleteAction.CASCADE)
private Notes notes;
}
@Embeddable
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@EqualsAndHashCode
public class UserNotesKey implements Serializable {
@Column(name = "USER_ID")
private Long userId;
@Column(name = "NOTES_ID")
private Long notesId;
}
Repositories
public interface UserRepository extends JpaRepository<User, Long> {
}
public interface NotesRepository extends JpaRepository<Notes, Long> {
}
public interface UserNotesRepository extends JpaRepository<UserNotes, UserNotesKey> {
List<UserNotes> findByUser(User user);
}
Тестовая служба
@Service
@Transactional
@RequiredArgsConstructor
public class TestService {
private final UserRepository userRepository;
private final UserNotesRepository userNotesRepository;
public User saveUser(User user) {
User newUser = new User();
user.setEmail(user.getEmail());
return userRepository.save(user);
}
public UserNotes saveNotes(User user, Notes notes) {
UserNotes userNotes = new UserNotes();
userNotes.setUser(user);
userNotes.setNotes(notes);
return userNotesRepository.save(userNotes);
}
public List<Notes> getNotes(User user) {
return userNotesRepository.findByUser(user)
.stream()
.map(UserNotes::getNotes)
.collect(Collectors.toList());
}
}