2

I seem to be having an issue with mapping a collection in hibernate where the key and the resource are both entities to be mapped by hibernate.

Whereas from the documentation (my main resource for this issue has been this, but I of course welcome any others: http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/collections.html) it would appear that this should be a relatively simple task, I just can't seem to get the key of the map to persist.

My code as it stands looks like this:

Parent class:

@Entity
public class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @MapKey
    @MapKeyClass(Key.class)
    @ManyToMany(cascade = CascadeType.ALL)
    private Map<Key, Resource> map;

Key class:

@Table(name="ParentKey")
@Entity
public class Key implements Comparable<Key> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "hierarchyKey")
    private int key;

The resource class is a relatively simple POJO and persists fine, so I would assume that the issue is not in that class.

I did come across the annotation @MapKeyManyToMany in some documentation on the hibernate forums, but I believe this has since been deprecated.

The schema of the database is unimportant at this stage, the main concern is simply making sure everything persists to the database. We're using MySQL for the underlying database.

As I'm sure you can probably guess, any search involving the words map, hibernate, entity and key return a large amount of questions not related to this issue, though I'm sure this must be a situation that occurs quite often in terms of mapping situations.

I don't often submit questions, but I am an active reader, so please let me know if any more info is required.

1
  • @axtavt While the resource persists to the database fine, the Key, which should also be persisted, does not. Commented Sep 12, 2012 at 15:58

1 Answer 1

1

This works as specified. Operations are not cascaded to the key of the map. They are cascaded only to the value. In documentation this is told with following words:

When the target collection is a java.util.Map, the cascade element applies to the map value.

Key must be persisted separately.

Sign up to request clarification or add additional context in comments.

2 Comments

This has definitely put me on the right track, do you know of a way to persist the key in the same way as the value?
This certainly helped, and while not a complete solution, did shape the path of the eventual solution I implemented, thanks. I ended up refactoring so that the key was of type Integer, which persists fine with a cascade.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.