A-->B 有两个..How JPA do ?

Class B is easy:
import java.io.Serializable;
import javax.persistence.*;

/**
* Entity implementation class for Entity: B
*
*/
@Entity
public class B implements Serializable {

public B() {
super();
}

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private int id;
private String name;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Class A is easy too, but it contains two B, one is named 'b1', the other 'b2':

import java.io.Serializable;
import javax.persistence.*;
import static javax.persistence.CascadeType.PERSIST;
import static javax.persistence.CascadeType.REMOVE;

/**
* Entity implementation class for Entity: A
*
*/
@Entity
public class A implements Serializable {

public A() {
super();
}

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private int id;

@OneToOne(cascade = { PERSIST, REMOVE })
private B b1;
@OneToOne(cascade = { PERSIST, REMOVE })
private B b2;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public B getB1() {
return b1;
}

public void setB1(B b1) {
this.b1 = b1;
}

public B getB2() {
return b2;
}

public void setB2(B b2) {
this.b2 = b2;
}

}

It is nothing serious, A knows which is b1, and which is b2, in the database it is saved like this(the table A):
ID B1_ID B2_ID

Try it:

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
B b1 = new B();
b1.setName("b1");
B b2 = new B();
b2.setName("b2");

A a = new A();
a.setB1(b1);
a.setB2(b2);

OperateData.create(a);

a = (A) OperateData.find(a);
System.out.println("b1:" + a.getB1().getName());
System.out.println("b2:" + a.getB2().getName());
}

}

You can see in table A:
ID B1_ID B2_ID
1 1 2

That's great, maybe we should try the 'OneToMany' or 'ManyToMany'....

----------------------

Don't set b2's value, what will happen ? If you have read the 'A-->List<B> 有两个..How JPA do ?', you may think there will be a error message printed.

But, there is nothing, yes, in the table A, you can save an 'A' that have the b1's value but don't have b2's. Think about it.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值