A-->List 有两个..How JPA do ?
程序员文章站
2022-03-02 15:30:55
...
Compare to the previous one(I mean 'A-->B 有两个..How JPA do ?'), I only add a constructor to Class B:
This is A -> List<B> , so the Class A:
Let's see the table A first:
There is only one field -- ID.
But, there is another table -- A_B, so we know, there is only one table exists between two relational entities.
A_B:
A_ID B2_ID B1_ID
Try it:
There is an error message -- '列“B2_ID”无法接受空值。'
What should we do ? Maybe I can add a property as Class B \'s state.
But, why don't use two different B ?
import java.io.Serializable;
import javax.persistence.*;
/**
* Entity implementation class for Entity: B
*
*/
@Entity
public class B implements Serializable {
public B() {
super();
}
public B(String name){
super();
this.name = name;
}
@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;
}
}
This is A -> List<B> , so the Class A:
import static javax.persistence.CascadeType.PERSIST;
import static javax.persistence.CascadeType.REMOVE;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
* Entity implementation class for Entity: A
*
*/
@Entity
public class A implements Serializable {
public A() {
super();
}
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private int id;
@OneToMany(cascade = { PERSIST, REMOVE })
private List<B> b1;
@OneToMany(cascade = { PERSIST, REMOVE })
private List<B> b2;
public List<B> getB1() {
return b1;
}
public void setB1(List<B> b1) {
this.b1 = b1;
}
public List<B> getB2() {
return b2;
}
public void setB2(List<B> b2) {
this.b2 = b2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Let's see the table A first:
There is only one field -- ID.
But, there is another table -- A_B, so we know, there is only one table exists between two relational entities.
A_B:
A_ID B2_ID B1_ID
Try it:
import java.util.ArrayList;
import java.util.List;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<B> b1 = new ArrayList<B>();
b1.add(new B("b1"));
b1.add(new B("b1."));
List<B> b2 = new ArrayList<B>();
b2.add(new B("b2"));
b2.add(new B("b2."));
A a = new A();
a.setB1(b1);
a.setB2(b2);
OperateData.create(a);
a = (A) OperateData.find(a);
for(B b : a.getB1()){
System.out.println("b1:" + b.getName());
}
for(B b : a.getB2()){
System.out.println("b2:" + b.getName());
}
}
}
There is an error message -- '列“B2_ID”无法接受空值。'
What should we do ? Maybe I can add a property as Class B \'s state.
But, why don't use two different B ?