mikeb
mikeb

Reputation: 11267

Hibernate Annotation on parent fields

I have a class that is a POJO with no special Hibernate annotations or information, like so:

public class Parent{
   Long id;
   String foo;
   String bar;
   /* ... getters and setters, toString(), etc... */
}

I would like to create a child class that has the Hibernate annotations on it. The idea is that the first class will not have any dependencies on it, and the second will have all of the JPA/Hibernate specific stuff. How can I do that without re-creating all the fields in the parent? I would like to put Hibernate annotations on the class

@Entity
public class PersistentChild extends Parent{
  // ????
}

Upvotes: 1

Views: 2039

Answers (2)

meskobalazs
meskobalazs

Reputation: 16041

You can use the @MappedSuperclass annotation on the POJO, then add the other annotations, as it were a normal JPA entity. But in this case, the annotations will only affect the entity classes, which are inheriting from it. Example:

@MappedSuperclass
public class Parent implements Serializable {
     @Id
     Long id;
     @Column(name = "foo", required = true)
     String foo;
     @Column(name = "bar", required = false)
     String bar;
     /* ... getters and setters, toString(), etc... */
}

If you really do not want to modify the superclass, you can use a mapping file:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm 
            http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
    <mapped-superclass class="Parent">
        <!-- add your mapping here -->
    </mapped-superclass>
</entity-mappings>

Alternative approach

Also, you can just add the @MappedSuperclass annotation, then define all properties like this:

@Entity
@AttributeOverrides({
    @AttributeOverride(name = "foo", column=@Column(name = "foo", required = true)),
    @AttributeOverride(name = "bar", column=@Column(name = "bar", required = false))
})
public class PersistentChild extends Parent {
    @Id @GeneratedValue
    Long id;
}

Upvotes: 4

trust_nickol
trust_nickol

Reputation: 2114

If you want to externalize the mapping you have to use xml-mapping file.

Upvotes: 0

Related Questions