0

My situation: I have one DB table for Object and a separate DB table for Object's extra info. Object is identified by autogenerated serial ID, Object's extra info has the same value as it's PK, so there is one-to-one relation.

I mapped Object's extra info within the instance of Object. It works fine for reading, but I am struggling while trying to save new record into DB.

Object side reference looks like this:

@JoinColumn(name = "object_id", referencedColumnName = "object_id")
@OneToOne(cascade = CascadeType.ALL)
private ObjectExtraInfo detail;

PK column in Object's extra info:

@Id
@NotNull
@Column(name = "object_id")
private Integer objectId;

I am using EntityManger.merge(), because there are couple of other DB tables referenced, EntityManager.persist() would be forcing me to deal with propper identification of DB entities.

It is no problem to achieve new Object record being saved, but the best I can do with attached Object's extra info was that it appears in DB with zero as PK. The auto-generated value of the new Object record is not distributed into Object's extra info. And it is impossible to change it afterwards while it is PK.

I am pretty sure my JPA annotations are messed up, especially on Object's extra info side. But so far I was unable to figure out the right approach.

Ellrohir
  • 1,017
  • 1
  • 14
  • 32
  • You need to actually tell the JPA provider that you want to use a shared primary key model. See here http://stackoverflow.com/questions/5805306/onetoone-between-two-tables-with-shared-primary-key or here http://stackoverflow.com/questions/6833370/jpa-onetoone-with-shared-id-can-i-do-this-better or here https://dzone.com/articles/onetoone-shared-primary-key – Alan Hay Dec 14 '16 at 20:52
  • I tried approach described in http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association (chapter 2.2.5.1). But I am ending up either with `"Primary key on table (object) has a field with a null key value."` error message when I use `@Column(name = "object_id")` in **Object's extra info** or with `Column (objectid) not found in any table in the query (or SLV is undefined)` when I omit it. Any idea what could be wrong? – Ellrohir Dec 15 '16 at 09:23

0 Answers0