Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
436 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 {
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...