woniper

[JPA] @OneToOne, 1:1 관계 매핑 본문

Framework

[JPA] @OneToOne, 1:1 관계 매핑

Woniper 2015.05.12 01:32


  1. JPA란 무엇인가?
  2. JavaSE 환경에서 JPA 설정 및 CRUD
  3. JavaEE 환경(Spring)에서 JPA 설정 및 CRUD
  4. @OneToOne, 1:1 관계 매핑
  5. @OneToMany / @ManyToOne, 1:N / N:1 관계 매핑
  6. @ManyToMany, N:M 관계 매핑
  7. Entity 객체 생명주기(Lifecycle)와 Persistence Context

Table 관계도


Entity

@Entity
public class Person {

    @Id
    @GeneratedValue
    private int id;

    private String name;

    @OneToOne
    @JoinColumn(name = "cellular_id")
    private Cellular cellular;

    public Person() {}

    public Person(String name, Cellular cellular) {
        this.name = name;
        this.cellular = cellular;
    }

    // getter and setter    

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", cellular=" + cellular +
                '}';
    }
}

@Entity
public class Cellular {

    @Id
    @GeneratedValue
    private int id;

    private int number;

    public Cellular() {}

    public Cellular(int number) {
        this.number = number;
    }
    
    // getter and setter

    @Override
    public String toString() {
        return "Cellular{" +
                "id=" + id +
                ", number=" + number +
                '}';
    }
}

TEST

public class OneToOneTest {

	@Autowired
	private EntityManagerFactory entityManagerFactory;
	private EntityManager entityManager;

	@Test
	public void oneToOneTest() {
		Cellular cellular = new Cellular();
		cellular.setNumber(521);
		entityManager.persist(cellular);

		Person person = new Person();
		person.setName("woniper");
		person.setCellular(cellular);
		entityManager.persist(person);

		Assert.assertEquals(person.getCellular().getId(), cellular.getId());
	}

	@Before
	public void setUp() throws Exception {
		entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
	}

	@After
	public void after() {
		entityManager.getTransaction().commit();
		entityManager.close();
	}
}


0 Comments
댓글쓰기 폼