Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JPA在两个相关表格中保存和检索记录_Java_Jpa_Orm_Persistence.xml - Fatal编程技术网

Java 使用JPA在两个相关表格中保存和检索记录

Java 使用JPA在两个相关表格中保存和检索记录,java,jpa,orm,persistence.xml,Java,Jpa,Orm,Persistence.xml,在我的应用程序中,有两个模型具有@onetomany realationship。 我已经定义了房间和座位实体。我的第一个问题是seats集合总是返回null @实体 公共教室实现可序列化{ @身份证 @GeneratedValue(策略=GenerationType.AUTO) 私人长Id; 私有字符串名称; @OneToMany(mappedBy=“房间”) Set seats=新HashSet(); 受保护房间(){ } 公众座位(座位){ 座位设置关联房间(本); 座位。添加(座位);

在我的应用程序中,有两个模型具有@onetomany realationship。 我已经定义了房间和座位实体。我的第一个问题是seats集合总是返回null


@实体
公共教室实现可序列化{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私人长Id;
私有字符串名称;
@OneToMany(mappedBy=“房间”)
Set seats=新HashSet();
受保护房间(){
}
公众座位(座位){
座位设置关联房间(本);
座位。添加(座位);
}
公共房间(字符串名称){
this.name=名称;
}
公共字符串getName(){
返回此.name;
}
公共字符串getSeatString(){
String out=“seats:”;
如果(座位数!=null)
用于(座位:座位)
out+=seat.getName()+“”;
返回;
}
}
@实体
公共类席位实现可序列化{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私人长id;
私有字符串名称;
@许多酮
@JoinColumn(name=“roomId”)
包房;
受保护座椅(){
}
公共座位(字符串名称){
this.name=名称;
}
公共字符串getName(){
返回此.name;
}
公共空间集合关联房间(房间){
这个房间=房间;
}    
}

这是数据库操作中使用的代码。 我还需要帮助实现搜索查询,如“getSeatsByRoom(stringroom)”


@组件
公共类SeatServiceImpl实现SeatService{
@PersistenceContext私有实体管理器em;
@交易的
公众座位(座位){
em.1(座位);
}

公共列表您需要维护双向映射的两侧。这意味着您还需要将
房间
设置为您的
座位
s。将此添加到您的代码中:

a1.setAssociatedRoom(roomA);
a2.setAssociatedRoom(roomA);
“setAssociatedRoom()”是从Room类addSeat方法调用的

public void addSeat(Seat seat) {
      seat.setAssociatedRoom(this);
      seats.add(seat);
}
错了吗

List<Room> rooms = new ArrayList<Room>();
Room roomA = new Room("roomA");
Seat a1 = new Seat("a1");
Seat a2 = new Seat("a2");

SeatService.persist(a1);
SeatService.persist(a2);

roomA.addSeat(a1);
roomA.addSeat(a2);      

RoomService.persist(roomA);
a1.setAssociatedRoom(roomA);
a2.setAssociatedRoom(roomA);
public void addSeat(Seat seat) {
      seat.setAssociatedRoom(this);
      seats.add(seat);
}