Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend JPA entity to add attributes and logic

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.

like image 860
jmoreira Avatar asked Sep 24 '12 17:09

jmoreira


People also ask

Can an entity extend another entity?

Entity classes can extend non-entity classes, and non-entity classes can extend entity classes. Entity classes can be both abstract and concrete.

Can a JPA entity have multiple Onetomany associations?

You can have as many of them as you want.

What are inheritance strategies in JPA?

Inheritance Strategies Inheritance is the core concept of object oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies such as SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS.

What is @ID annotation in JPA?

@Id annotation is the JPA is used for making specific variable primary key.


1 Answers

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 {
    ...
}
like image 105
Ilya Avatar answered Oct 03 '22 22:10

Ilya