【问题标题】:Hibernate, select only parent class columns from a single table shared between parent and child classHibernate,仅从父类和子类共享的单个表中选择父类列
【发布时间】:2023-04-07 04:57:01
【问题描述】:

Hibernate:我需要从单个 db 表中仅选择父对象,这些对象映射到 hibernate 中的父类和子类。

这是简化的休眠表定义:

@Entity
@Polymorphism(type = PolymorphismType.EXPLICIT)
@Inheritance(strategy = InheritanceType. SINGLE_TABLE)
public class parent{
    @Id
    @Column(name="ID")
    @GeneratedValue(strategy=GenerationType.AUTO, generator="parent_gen")
    @SequenceGenerator(name="parent_gen", sequenceName="PARENT_SEQUENCE")
    private int parentID;

    @Column(name="name")
    private String name;

} 

@Entity
@Table(name = "childtable")
public class child extends parent{
 @Column(name="favoriteColor")
    private String favoriteColor;
}

在mysql数据库中,这是“childtable”的样子:

|id|name|favoriteColor|
|1|John|blue|
|2|Smith|red|
|3|Gary|yellow|

现在,我想从仅包含父列的子表中进行选择,并希望在 hql 中获取父对象。

类似:

Session session = HibernateUtil.getSessionFactory().openSession();

        Query query = session
                .createQuery("from parent where id <4");
         List<parent> result = query.list();

我没有将 DTYPE 引入子表,因为没有实例需要将父类插入子表。我只想在进行选择查询时区分父对象和子对象。

我怎样才能让它与hibernate一起工作?

更新 1: 我找到了一种通过运行它来解决问题的方法。我不确定这是否是解决问题的正确方法,但它确实有效。

Query query = session
                    .createQuery("select new parent(id,name) from parent where id <4");
             List<parent> result = query.list();

【问题讨论】:

    标签: mysql hibernate web hql java-ee-7


    【解决方案1】:

    我找到了一种通过运行它来解决问题的方法。我不确定这是否是解决问题的正确方法,但它确实有效。

    Query query = session
                    .createQuery("select new parent(id,name) from parent where id <4");
             List<parent> result = query.list();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      相关资源
      最近更新 更多