I have an employer table with schema containing userprofileId
The employer table as stated below is containing userprofileid which is primary key of user table
id int(11) (not NULL) PRI
userprofileid int(11) (not nUll)
organization_name varchar(50) (not nUll)
Now my requirement was create a JPA class for this employer.
Now we have Employer.java, with below entry.
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name="userProfileId", referencedColumnName="id" )
@Column( insertable=false ,updatable =false)
private UserProfile userProfile;
@Column(name = "organization_name")
private String organizationName;
Now hurdle is.
Our UserProfile is object is created in different method. Now i dont want to again add same value to userprofile table and so i made insertable = false and updatable = false in employer.java so that the field does not get updated;
No if i set the value of userprofile in employer object
it says
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.hcentive.core.user.UserProfile; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.hcentive.core.user.UserProfile
but if i dont set the user profile it gives below error.
Caused by: java.sql.SQLException: Field 'userprofileid' doesn't have a default value
Note for persisting I am using :
getJpaTemplate().persist(t);
Your Employer refers to an already existing user profile. If it already exists, it is in the database. If it is in the database, you must not create a new instance, but get it from the database. To get something from the database, you use the
EntityManager.find()orEntityManager.getReference()method (the second one doesn’t even do any select statement).So, remove the
insertableandupdatableflags from your annotation (the association is insertable), and use code similar to the following one: