Given a table (MY_TABLE_A
) that automatically increments it's id upon each new insertion (i.e. the first record in the database has it's ID attribute 1, the second record has it's ID attribute set to 2, the third record has it's ID attribute set to 3). The ID I am talking about is the table's primary key.
I also have another table (MY_TABLE_B
) that reference's the original table's primary key. When I try to persist both to my Oracle database, I get a org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()
What I want to accomplish: Whenever I persist an object to MY_TABLE_A
, I want MY_TABLE_B
to insert an object with the same ID that MY_TABLE_A
gets since it's auto incremented (wouldn't know what the next value is until it's inserted). To clarify, one id in Table A should have only one matching ID in Table B
Here are some snippets of my code below:
FirstClass:
@Entity
@Table(name = "MY_SCHEMA.MY_TABLE_A")
@Component
public class FirstClass implements Serializable {
@Id
@SequenceGenerator(name = "MY_SEQ", sequenceName = "MY_SCHEMA.MY_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQ")
@Column(name = "MY_ID")
private Integer myId;
// more variables, getters/setters
}
SecondClass:
@Entity
@Table(name = "MY_SCHEMA.MY_TABLE_B")
@SecondaryTable(name = "MY_SCHEMA.MY_TABLE_A", pkJoinColumns = @PrimaryKeyJoinColumn(name = "MY_ID", referencedColumnName = "MY_ID"))
@Component
public class SecondClass {
@Id
@Column(name = "MY_ID")
private Integer myId;
// more variables, getters/setters
}
Service Layer snippet where I insert new entries for each in Oracle:
firstClassService.insert();
secondClassService.insert();
Details on insert()
for firstClassService:
public void insert() {
FirstClass obj = new FirstClass();
getCurrentSession().persist(obj);
}
insert()
for secondClassService:
public void insert() {
SecondClass obj = new SecondClass();
getCurrentSession().persist(obj);
}
UPDATE
What FirstClass looks like now:
@Entity
@Table(name = "MY_SCHEMA.MY_TABLE_A")
@Component
public class FirstClass implements Serializable {
@Id
@SequenceGenerator(name = "MY_SEQ", sequenceName = "MY_SCHEMA.MY_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQ")
@Column(name = "MY_ID")
@OneToOne(mappedBy = "myId")
private Integer myId;
}
SecondClass:
@Entity
@Table(name = "MY_SCHEMA.MY_TABLE_B")
@SecondaryTable(name = "MY_SCHEMA.MY_TABLE_B", pkJoinColumns = @PrimaryKeyJoinColumn(name = "MY_ID", referencedColumnName = "MY_ID"))
@Component
public class SecondClass implements Serializable {
@Id
@JoinColumn(name = "MY_ID", referencedColumnName = "MY_ID")
@OneToOne
private Integer restRequestId;
}