views:

1229

answers:

3

In the following example, how can I save the value of role to the role with id=1 without loading it? I have tried:

Map user = new HashMap();

user.put("address","Address test"); user.put("role",1);

session.save("User",user);

But that results in:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.Map at org.hibernate.property.MapAccessor$MapGetter.get(MapAccessor.java:90)

And

Map user = new HashMap();

user.put("address","Address test"); user.put("role.id",1);

session.save("User",user);

Doesn't save the role, console shows this SQL: Hibernate: insert into user (ts, address) values (?, ?)

Any help will be greatly appreciated.

A: 

Looks like the role should be a map

Maurice Perry
A: 

From the top of my head, you need a Session working in map mode. I think something like this:

  SessionFactory sf = ...;
  Session s = sf.openSession();
  Session ds = s.getSession(EntityMode.MAP);

Then work with ds as you already attempted.

javashlook
A: 

The answer is:

Map user = new HashMap();

user.put("address","Address test");

user.put("role", session.load("Role",1));

session.save("User",user);

This sentence:

session.load("Role",1)

doesn't make hibernate hit the database and the reference to the role with id=1 is successfully persisted in the new user.

jmpeace