0

I have two tables. The structure is

Personal table Auto Id Number, int, Primary Key | Name, Varchar | Age, int |

Demographic table Auto id number, int, foreign key | Address, varchar |

I've created entity classes as below:

PersonalEntity.class

@Entity
@Table("Personal")
public class PersonalEntity {

@Id
@Column(name="Auto Id Number")   
private int id;

@Column(name="Name")
private String name;

@Column(name="Age")
private int age;

@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private DemographicEntity de;

DemographicEntity.class

@Id
@Column(name="Auto Id Number")   
private int id;

@Column(name="Address") 
private String address;

Dao Class

@Transactional
public PersonalEntity add(PersonalEntity pe, DemographicEntity de){
     pe.setDe(de);
     entitymanager.persist(pe);
     return pe;
}

I am using jpa with Microsoft SQL. I want to insert data into the Personal table first and the db will auto generate a primary key. That primary key is the foreign key of Demographic table. When I called the persist() I am getting the error

The INSERT statement conflicted with the FOREIGN KEY constraint. could not execute statement; contraint(null)

What am I doing wrong here? I want to insert data in the personal table and using the auto generated key, I want to insert data in the demographic table

Kiran Cyrus Ken
  • 379
  • 1
  • 3
  • 17

1 Answers1

0

You have to set optional=false on the OneToOne mapping to tell Hibernate that the FK may not be null

@OneToOne(cascade=CascadeType.ALL, optional=false)
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82