jpa에서는 저장시 repository.save 함수를 이용하여 저장합니다
Member
class처럼 @OneToMany나 @ManyToOne 필드들을 함께 저장 할 수 있습니다.
Member.java#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| @Entity
@Table(name = "tb_member")
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "member_seq")
public Integer memberSeq;
@Column
public String nickname;
@Expose
@OneToMany(
targetEntity = MemberInter.class
, cascade = CascadeType.ALL
, fetch = FetchType.EAGER
, mappedBy = "memberSeq")
public List<MemberInter> memberInterList;
}
|
MemberInter.java#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| @Entity
@Table(name="tb_member_inter")
@IdClass(value = MemberInterPk.class)
public class MemberInter {
@Id
@Column(name = "member_seq")
public Integer memberSeq;
@Id
@Column(name = "inter_seq")
public Integer interSeq;
@ManyToOne(
targetEntity = Inter.class
,cascade = CascadeType.ALL
,fetch = FetchType.LAZY
,optional = false
)
@JoinColumn(name = "inter_seq", referencedColumnName = "inter_seq"
, insertable = false, updatable = false)
public Inter inter;
}
|
@JoinColumn에 insertable, updateable을 추가 하여 false 했습니다
Test method#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| @Test
public void testSave() throws Exception{
logger.info("------------ jpa test starting.... ------------------------");
Member data = memberRepository.findByNickname("111");
logger.info("data={}", gson.toJson(data));
data.nickname = "222";
MemberInter memberInter = new MemberInter();
memberInter.interSeq = 28;
memberInter.memberSeq = data.memberSeq;
MemberInter memberInter2 = new MemberInter();
memberInter2.interSeq = 29;
memberInter2.memberSeq = data.memberSeq;
data.memberInterList.add(memberInter);
data.memberInterList.add(memberInter2);
// 실제 저장. (member클래스를 저장. 한다)
memberRepository.save(data);
logger.info("------------ jpa test ended.... ------------------------");
}
|
위 test method를 실행하면 아래와 같이 sql가 실행됩니다#
1
2
3
4
5
| ...
...
Hibernate: insert into tb_member_inter (inter_seq, member_seq) values (?, ?)
Hibernate: insert into tb_member_inter (inter_seq, member_seq) values (?, ?)
Hibernate: update tb_member set nickname=? where member_seq=?
|
로그에서 insert into가 두번 호출 되고 update도 한번 실행되는것을 확인 할 수 있습니다.