扩展JPA实体以添加属性和逻辑 [英] Extend JPA entity to add attributes and logic

查看:627
本文介绍了扩展JPA实体以添加属性和逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道是否可以通过扩展一些POJO JPA实体(使用 hibernate 提供者)来添加一些属性和行为,然后使entityManager返回扩展对象而不仅仅是pojo实体,如以下示例所示:



POJO JPA实体类

  @Entity 
@Table(test)
public class Test实现Serializable {
}

扩展类

  public class ExtendedTest extends Test {
...
}

获取扩展类的对象

 列表与LT; ExtendedTest> extendedList = entityManager.createNamedQuery(ExtendedTest.findByFoo)。setParameter(foo,bar)。getResultList(); 

我正在评估的另一种可能方式是使用复合实体扩展funcionality并委托所有setter和getters ,但这可能意味着大量表的工作:

  public class ExtendedTest2 {
private Test test;

public ExtendedTest2(测试测试){
this.test = test;
}

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

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

...
}

任何建议将非常感激。

解决方案

使用 @Inheritance @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Test {
...
}

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

@MappedSuperclass

  @MappedSuperclass 
public class Test {
...
}

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


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.

解决方案

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

这篇关于扩展JPA实体以添加属性和逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆