4

I have the entities "User" and "Customer":

@Entity
@Table(name = "USR_USER")
public class User extends PersistentObject {

   [...]

   @Any(metaColumn = @Column(name = "USR_OWNERTYPE"))
   @AnyMetaDef(idType = "long", metaType = "string", metaValues = {
         @MetaValue(targetEntity = Customer.class, value = "CST"),
         @MetaValue(targetEntity = Client.class, value = "CLT") })
   @JoinColumn(name = "USR_OWNERID")
   private PersistentObject owner;
}

@Entity
@Table(name = "CST_CUSTOMER")
public class Customer extends PersistentObject {

   @Id
   @GeneratedValue
   @Column(name="CST_ID")
   private long id;

   [...]

   // @OneToMany(mappedBy = "owner")
   private transient Set<User> users;
}

Running this (using spring), I got the following exception:

Caused by: org.hibernate.MappingException: Foreign key (FK35B91BB65D577CEF:USR_USER [USR_OWNERTYPE,USR_OWNERID])) must have same number of columns as the referenced primary key (CST_CUSTOMER [CST_ID])

I do not understand this, because I mapped the class "Customer" in @AnyMetaDef (in "User") to the constant "CST".

What am I doing wrong?

Thanks in advance for any help Thomas

Thomas777
  • 41
  • 1

1 Answers1

1

"It is impossible to specify a foreign key constraint for this kind of association." -- http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-types-anymapping

Edit: What you would want for the opposite end of your @Any is a @OneToAny, and that doesn't exist. It may be that you're using the @Any mapping in an inappropriate place. Again from the docs: "This is not the usual way of mapping polymorphic associations and you should use this only in special cases. For example, for audit logs, user session data, etc."

Take a hard look at inheritance mapping, and see if one of those isn't a more appropriate way to map your relationship.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • It seems to be that the foreign keys are created automatically by hibernate. (I am using the hibernate-property "hibernate.hbm2ddl.auto" => "create" with HSQL) How can I disable the creation of foreign keys for that relationship? – Thomas777 Aug 24 '11 at 22:25
  • Does the error happen with or without the `@OneToMany` that's commented out above? Without the `@OneToMany`, I believe that should be a valid `@Any` mapping. I'd expect the FK error to be coming from the `@OneToMany`. – Ryan Stewart Aug 25 '11 at 01:50
  • You are right, the FK results from the `@OneToMany`. But I think I need the `@OneToMany`, or is there an alternative? – Thomas777 Aug 25 '11 at 16:08