【问题标题】:How to dynamic load hibernate Entity based on id and class name如何根据 id 和类名动态加载休眠实体
【发布时间】:2016-06-25 01:40:56
【问题描述】:

我正在映射一个现有数据库,其中有几个表,其中包含以下字段: 任务(表) external_id int(100) 类名 varchar(300)

这些字段代表一个类层次结构,它们可以是组或用户 单个表可能具有以下值:

external_id  class_name
1            com.mycompany.User 
3            com.mycompany.User
1            com.mycompany.Group

类层次结构是这样的:

User extends TaskExecutor
Group extends TaskExecutor

数据库中的一张表是Task

class Task{
    TaskExecutor taskExecutor
    ....
}

是否可以配置 Hibernate 以根据 class_name 数据库属性为适当的类实例化代理?

UserGroup 类在数据库中有单独的表

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    您可以使用 Hibernate 创建类型化的类层次结构:

    @Entity
    @Table(name = "main_table")
    @Inheritance(strategy = InheritanceType.JOINED)
    @DiscriminatorColumn(name = "class_name") // The column to store the type
    public abstract class AbstractMainTable {
        // Your entity declaration here
    
        // The type must be declared with insertable and updatable to false
        // or it can be omitted completely if not necessary
        @Column(name = "class_name", insertable = false, updatable = false)
        private String className;
    
    }
    

    然后你可以声明你的扩展

    @Entity
    @Table(name = "extended_table")
    @DiscriminatorValue(value = "myClassType") // Optional, the type value stored in the column IF different from the real classname
    public class MyClass extends AbstractMainTable {
        // This automatically inherits the fields from AbstractMainTable
    }
    

    【讨论】:

    • 请再次查看我的问题,我添加了更多详细信息。这是一个现有的数据库,并且用户和组表已经存在
    • 举一个完整的例子,至少有两个表,它们的模式和数据。因为现在我看不出我的答案不合适。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多