19

I need to know if it's possible to add some attributes and behaviours to some POJO JPA entity (using hibernate provider) by extending it, and then to make entityManager to return extended objects instead of just pojo entitys, like the following examples:

POJO JPA Entity Class

@Entity
@Table("test")
public class Test implements Serializable {
}

Extended Class

public class ExtendedTest extends Test {
...
}

Fetching Extended Class's objects

List<ExtendedTest> extendedList = entityManager.createNamedQuery("ExtendedTest.findByFoo").setParameter("foo", "bar").getResultList();

The other possible way i'm assessing is extending funcionality with a composite entity and delegating all setters and getters, but this could mean a lot of work with huge tables:

public class ExtendedTest2 {
    private Test test;

    public ExtendedTest2(Test test) {
        this.test = test;
    }

    public getFoo() {
        return test.getFoo();
    }

    public getBar() {
        return test.getBar();
    } 

    ...
}

Any suggestions will be very appreciated.

jmoreira
  • 1,556
  • 2
  • 16
  • 26
  • I don't think is possible as you can happily put your logic and other attributes in the entity class. – dcernahoschi Sep 24 '12 at 18:13
  • 1
    I actually can add other attributes and logic to my entity class but not "happily", my idea is to keep entities like POJO and to hold only table representation attributes, in fact thats precisely why i create this question in the first place. – jmoreira Sep 24 '12 at 18:21

1 Answers1

38

Using @Inheritance

@Entity
@Table(name="TEST")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Test {
    ...
}

@Entity
public class ExtendedTest 
    extends Test {
    ...
}  

or @MappedSuperclass

@MappedSuperclass
public class Test {
    ...
}

@Entity
public class ExtendedTest 
    extends Test {
    ...
}
Ilya
  • 29,135
  • 19
  • 110
  • 158
  • 7
    Just if someone get to this, idk if it's wrong or because the version (JPA 2.1, eclipse link), but i had to add the `@Inheritance(strategy=InheritanceType.SINGLE_TABLE)` annotation in the child class, not the parent – rekiem87 May 08 '14 at 18:57
  • 2
    Just for reference: when using `@Entity` on an abstract class, and each derived entity should create it's own table, in this case you must use `@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)` on the *abstract parent* table! – membersound Apr 02 '15 at 07:56
  • How can we do this extension while we use same name for classes but in different packages? I want to have this possibility to extend the entities for example for `toString` function but I don't want to use different name for entities! – MJBZA May 28 '20 at 06:44
  • 3
    `@MappedSuperclass` on the extended class (parent class) worked for me. – javaPlease42 Jun 09 '22 at 21:26