#30 jpa basic: proxy - cascade

This commit is contained in:
haerong22
2023-02-01 00:44:36 +09:00
parent ab9ee6cb4c
commit 3c35236261
4 changed files with 136 additions and 2 deletions

View File

@@ -0,0 +1,41 @@
package com.hello.jpa.proxy.ex01;
import javax.persistence.*;
@Entity
public class Child {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}

View File

@@ -0,0 +1,44 @@
package com.hello.jpa.proxy.ex01;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
Child child1 = new Child();
Child child2 = new Child();
Parent parent = new Parent();
parent.addChild(child1);
parent.addChild(child2);
em.persist(parent);
em.flush();
em.clear();
Parent findParent = em.find(Parent.class, parent.getId());
findParent.getChildren().remove(0);
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
em.close();
}
emf.close();
}
}

View File

@@ -0,0 +1,47 @@
package com.hello.jpa.proxy.ex01;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Parent {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Child> children = new ArrayList<>();
public void addChild(Child child) {
children.add(child);
child.setParent(this);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}

View File

@@ -30,8 +30,10 @@
<!-- <class>com.hello.jpa.inheritance.ex00.Movie</class>-->
<!-- <class>com.hello.jpa.inheritance.ex01.Member</class>-->
<!-- <class>com.hello.jpa.inheritance.ex01.Team</class>-->
<class>com.hello.jpa.proxy.ex00.Member</class>
<class>com.hello.jpa.proxy.ex00.Team</class>
<!-- <class>com.hello.jpa.proxy.ex00.Member</class>-->
<!-- <class>com.hello.jpa.proxy.ex00.Team</class>-->
<class>com.hello.jpa.proxy.ex01.Parent</class>
<class>com.hello.jpa.proxy.ex01.Child</class>
<properties>
<!-- 필수 속성 -->