我有2个实体块和子块,其中sql FOREIGN KEY(id_block)REFERENCES块(id_block),
@Entity
@Table(name = "block")
public class Block {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private long id_block;
@Column
private String name;
@OneToMany(mappedBy = "block",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<Subblock> subblock = new ArrayList<>();
public Block() {
}
public long getId_block() {
return id_block;
}
public void setId_block(long id_block) {
this.id_block = id_block;
}
public Block(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Subblock> getSubblock() {
return subblock;
}
public void setSubblock(List<Subblock> subblock) {
this.subblock = subblock;
}
}
@Entity
@Table(name = "subblock")
public class Subblock {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private long id_subblock;
@ManyToOne
@JoinColumn(name="id_block")
private Block block;
@Column
String name;
public Subblock() {
}
public long getId_subblock() {
return id_subblock;
}
public void setId_subblock(long id_subblock) {
this.id_subblock = id_subblock;
}
public Block getBlock() {
return block;
}
public void setBlock(Block block) {
this.block = block;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
使用服务将Block对象合并到DB的主要方法。
Block block = new Block();
Subblock subblock = new Subblock();
List<Subblock>subblockList= new ArrayList();
subblock.setName(messageSource.getMessage("block_1.1",new String[]{},locale));
subblockList.add(subblock);
block.setName(messageSource.getMessage("block_1",new String[]{},locale));
block.setSubblock(subblockList);
try {
ratingService.add(block);
}
catch (NullPointerException e){
e.printStackTrace();
}
}
我如何合并id_block出现在子块表中的对象?虽然在mappedBY的帮助下我连接了类。或者我必须使用双向通信来唤醒它吗?