使用休眠获得更少的列 [英] Getting fewer columns with hibernate

查看:103
本文介绍了使用休眠获得更少的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个11列的表,但我需要在我的应用程序中只有2个表,我使用的是spring / hibernate / DAO组合。现在我有一个包含所有11个字段的域类,以及映射表中所有11个列的映射文件。

解决方案

或者:


  1. 使用投影 - Pro:无需添加 - Con:不是类型安全的(结果是 List 行是 Object [])

      select f.foo, f.bar from FatEntity f 


  2. 在SELECT子句中使用构造函数表达式(指定的类不需要是实体或映射到数据库) - Pro:类型安全解决方案 - Con:更多的类,除非您重复使用 FatEntity 作为持有者,在这种情况下,许多字段将会是 null

      select new com.acme.FatEntityDetails(f .id,f.foo,f.bar)来自FatEntity f 

    请注意,如果一个实体类名是在 SELECT NEW 子句中指定的,所得到的实体实例处于 new 状态(没有持久性标识)。


  3. 使用ano其实体映射在同一张表上只有必要的字段 - Pro:它是一个真正的实体,你可以修改和更新 - Con:更多的类。

     <来自LightEntity的code> 


#2和#3之间的差异是:


  • 2并不要求持有者完全是一个实体。

    h1>


  • #2中的持有者可以是映射到另一个表上的实体。如果#2返回实体,则它们处于新状态(这可能是个问题,或者不是)。

I have a table with 11 columns, but I need to get only 2 of them in my application, I'm using spring/hibernate/DAO combination. For now I have a domain class which includes all 11 fields, and mapping file which maps all 11 columns in table. How do I use get just 2 of them not all?

解决方案

Either:

  1. Use projections - Pro: nothing to add - Con: Not typesafe (the result is a List of rows where each row is anObject[]):

    select f.foo, f.bar from FatEntity f
    

  2. Use a constructor expression in the SELECT clause (the specified class is not required to be an entity or to be mapped to the database) - Pro: typesafe solution - Con: More classes, unless you reuse FatEntity as holder in which case many fields will be null:

    select new com.acme.FatEntityDetails(f.id, f.foo, f.bar) from FatEntity f
    

    Note that if an entity class name is specified in the SELECT NEW clause, the resulting entity instances are in the new state (no persistent identity).

  3. Use another entity mapped on the same table with only the required fields - Pro: It's a real entity that you can modify and update - Con: More classes.

    from LightEntity
    

The main differences between #2 and #3 are:

  • 2 doesn't require the holder to be an entity at all.

  • the holder in #2 could be an entity mapped on another table.
  • if #2 returns entities, they are in a new state (this might be a problem, or not).

这篇关于使用休眠获得更少的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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