Hi, I'm new to Hibernate and having problems getting a foreign key mapping working.
I have the following simple table structure which maps users to preferences:
Code:
CREATE TABLE Users
(
userId int IDENTITY NOT NULL,
userName varchar(50) NOT NULL
)
CREATE TABLE UserPreferences
(
prefId int IDENTITY NOT NULL ,
userId int NOT NULL ,
preferenceString text NOT NULL
)
My class implementations are as below (based on the Hibernate Owner/OwnerAddress example):
Code:
@Entity
@Table (name="Users")
public class User
{
@Id
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column (name="userId")
private Integer userId;
@Column (name="userName")
private String userName;
@OneToOne (cascade=CascadeType.ALL)
@JoinColumn (name="userId")
private Preferences preferences;
// get/set methods...
}
@Entity
@Table (name="UserPreferences")
public class Preferences
{
@Id
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column (name="prefId")
private Integer prefId;
@GeneratedValue(generator = "fk")
@GenericGenerator (strategy = "foreign", name = "fk",
parameters = @Parameter(name="property", value="user"))
@Column (name="userId")
private Integer userId;
@OneToOne (mappedBy="preferences", optional=false)
private User user;
@Column (name="preferenceString")
private String preferenceString;
// get/set methods...
}
and finally my test case is as follows:
Code:
@Test
public void testSaveUserAndPreference() throws Exception
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = new User();
Preferences prefs = new Preferences();
prefs.setPreferenceString("test preferences");
prefs.setUser(user);
user.setPreferences(prefs);
user.setUserName("test user with prefs");
session.persist(user);
tx.commit();
session.close();
HibernateUtil.shutdown();
}
The problem I am having is that the userId is not being set on the UserPreference and hence gives me an insert exception:
Code:
Hibernate:
/* insert core.User
*/ insert
into
Users
(userName)
values
(?)
Hibernate:
/* insert core.Preferences
*/ insert
into
UserPreferences
(preferenceString, userId)
values
(?, ?)
12:08:22,265 WARN JDBCExceptionReporter:77 - SQL Error: 515, SQLState: 23000
12:08:22,265 ERROR JDBCExceptionReporter:78 - Cannot insert the value NULL into column 'userId', table 'dbo.UserPreferences'; column does not allow nulls. INSERT fails.
Any ideas what I am doing wrong?