A-->B 有两个..How JPA do ?
程序员文章站
2022-02-12 21:24:13
...
Class B is easy:
Class A is easy too, but it contains two B, one is named 'b1', the other '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:
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.
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.
上一篇: JPA 多对多实例配置
下一篇: css中注释引起样式无效不可用