简体   繁体   中英

JPA persist one-to-one persistence with non-existing entity from one side

I have an old database where there are two tables with implicit association between them:

booking

- id
- name
... some other fields...

and

booking_info
- id
- booking_id
... some other fields...

Due to the current database design there no any constraints between these two tables, which means that one booking entry may exist without any booking_info entries and vice versa. booking_id in booking_info table is an implicit foreign key which refers to booking table (column id ), but it also may refer to the absent booking.

I have created the following JPA mapping for these tables:

@Entity
public class Booking {

    @Id
    private Long id;
    private String name;

    // getters & setters
}

and

@Entity
public class BookingInfo {

    @Id
    private Long id;

    @OneToOne
    @JoinColumn(name = "booking_id")
    private Booking booking

    // getters & setters

}

Now I need to be able to persist a BookingInfo entity even if there's no related Booking entry in the database.

BookingInfo bookingInfo = new BookingInfo();
bookingInfo.setId(1);
Booking booking = new Booking();
booking.setId(182); // let's say that there's no booking with id 182 in my database, but I still need to persist this bookingInfo
bookingInfo.setBooking(booking);

bookingInfoRepository.save(bookingInfo); // using Spring Data JPA

If I run this code then I get javax.persistence.EntityNotFoundException since booking with id 182 is absent.

What would be the proper workaround for my case using JPA or Hibernate. Btw, I also tried to use Hibernate's @NotFound annotation. As a result, save method doesn't throw javax.persistence.EntityNotFoundException and entity gets persisted int the database, but the problem is that booking_id in the database always null.

Any help would be appreciated.

I am not sure my answer will help you or not, but the result you are getting perfectly make sense. As you are setting a JPA object, and that object is not present, hence the null value is saved. If you want to save 182 as an integer, you don't do JPA relationship. Instead, you just use booking-id as an integer field in booking-info. And that makes sense because you actually do not have the relationship between those tables which the JPA is trying to achieve.

But I am sure you just want to save 182 and as well as maintain the JPA relationship. And I am sure you already know it, but DB integrity is not being maintained with the approach you are taking. I am sure there is enough reason behind that. But my recommendation would be applying proper constraints in the DB and then in JPA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM