Extend JPA entity to add attributes and logic

佐手、 提交于 2019-12-30 17:25:15

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/12570251/extend-jpa-entity-to-add-attributes-and-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!