spring data JPA null主键错误

时间:2018-03-02 23:03:04

标签: postgresql spring-data-jpa

这是我的数据实体

@Entity
@Table(name = "hotel")
@Data
public class Hotel  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "hotel_id", updatable = false)
    @JsonIgnore
    private int id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "room_price")
    private RoomPrice roomPrice;
}

@Entity
@Table(name = "room_price")
@Data
public class RoomPrice {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "room_price_id", updatable = false)
    @JsonIgnore
    private int roomPriceId;

    @Column(name = "price")
    @Min(0)
    private double price;

    @Column(name = "currency_type")
    @NotEmpty
    @Size(min = 3, max = 3)
    private String currency;
}

SQL:

CREATE TABLE IF NOT EXISTS room_price (
  room_price_id INTEGER PRIMARY KEY,
  price         SMALLINT,
  currency_type VARCHAR(3) NOT NULL
);
ALTER TABLE hotel
  ADD
  COLUMN room_price INTEGER REFERENCES room_price (room_price_id);

hotel.setRoomPrice(price); hotelDao.save(hotel); throw room_price_id null value error message。 使用cascade.all时,在存储酒店实体时,它还应存储价格实体。我做错了什么? 感谢。

1 个答案:

答案 0 :(得分:0)

由于您使用的是GenerationType.IDENTITY策略,因此您应该使用serialbigserial类型room_price_id让Postgres自动生成您的主键。