-
-
Save okihouse/78dacfeb37f4753628433beb1b591f99 to your computer and use it in GitHub Desktop.
Spring Data JPA - How to insert child entities with composite key?
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 | |
@Table(name = "like") | |
@Data | |
public class Like { | |
@EmbeddedId | |
private LikeKey likeKey; | |
@Column(name = "word") | |
private String word; | |
@MapsId(value = "userNo") | |
@ManyToOne(optional = false, targetEntity = User.class) | |
@JoinColumn(name = "uno") | |
private User user; | |
@Embeddable | |
@Data | |
@NoArgsConstructor | |
@AllArgsConstructor | |
public static class LikeKey implements Serializable { | |
private static final long serialVersionUID = 2116470670954200809L; | |
@Column(name = "likeNo") | |
private Long likeNo; | |
@Column(name = "uno") | |
private Long userNo; | |
} | |
} |
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
@RunWith(SpringJUnit4ClassRunner.class) | |
@SpringApplicationConfiguration(classes = SpringJpaTestApplication.class) | |
@WebAppConfiguration | |
@IntegrationTest("server.port:0") | |
public class Test { | |
@Autowired | |
private UserRepository userRepository; | |
@org.junit.Test | |
public void application() throws Exception { | |
User user = new User(); | |
user.setType(USER_TYPE.USER); | |
Like like = new Like(); | |
LikeKey likeKey = new LikeKey(); | |
likeKey.setLikeNo(1L); | |
like.setLikeKey(likeKey); | |
like.setWord("word"); | |
like.setUser(user); | |
user.getLikes().add(like); | |
userRepository.save(user); | |
} | |
} |
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 | |
@Table(name = "user") | |
@Data | |
public class User { | |
@Id | |
@GeneratedValue | |
@Column(name = "uno") | |
private Long userNo; | |
@Column(name = "user_type") | |
@Enumerated(EnumType.STRING) | |
private USER_TYPE type; | |
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL) | |
private List<Like> likes = new ArrayList<>(); | |
public enum USER_TYPE {USER, ADMIN} | |
@Override | |
public String toString() { | |
return "User [userNo=" + userNo + ", type=" + type + ", likes=" + likes + "]"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment