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

时间:2014-11-13 12:06:47

标签: java jpa orm persistence.xml

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


@Entity
public class Room implements Serializable {   
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   private Long Id;
   private String name;
   @OneToMany(mappedBy = "room")
   Set<Seat> seats = new HashSet();

   protected Room() {

   }

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

   public Room(String name) {
      this.name = name;
   }

   public String getName() {
      return this.name;
   }

   public String getSeatsToString() {
      String out = "seats:";

      if(seats != null)
         for (Seat seat : seats)
            out += seat.getName()+ " ";
      return out;
        }
}


@Entity
public class Seat implements Serializable {

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

   @ManyToOne       
   @JoinColumn(name = "roomId")        
   private Room room;

   protected Seat() {

   }

   public Seat(String name) {
      this.name = name;      
   }

   public String getName() {
      return this.name;
   }

   public void setAssociatedRoom(Room room) {
      this.room = room;    
   }    
}


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


@Component
public class SeatServiceImpl implements SeatService {

    @PersistenceContext private EntityManager em;

    @Transactional
    public void persist(Seat seat) {
        em.persist(seat);
    }

    public List<Seat getAllSeats() {
       TypedQuery<Seat> query = em.createQuery(
            "SELECT c FROM Seat c", Seat.class);
       return query.getResultList();
    }

    public List<Seat getSeatsByRoom(String room) {
        TypedQuery<Seat> query = em.createQuery(
                    "SELECT s FROM Seat s, Room r where s.name = :room and (s.roomId= c.Id)", Seat.class);

        query.setParameter("room", room);
        return query.getResultList();
    }
}


持久物体:

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);

2 个答案:

答案 0 :(得分:0)

您需要维护双向映射的两面。这意味着您还需要将room设置为seat。将其添加到您的代码中:

a1.setAssociatedRoom(roomA);
a2.setAssociatedRoom(roomA);

答案 1 :(得分:0)

&#34; setAssociatedRoom()&#34;从Room class addSeat方法调用

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

是不是错了?