【问题标题】:How to map dynamic SQL column to Hibernate Entity object?如何将动态 SQL 列映射到 Hibernate Entity 对象?
【发布时间】:2023-03-29 16:51:01
【问题描述】:

我正在使用一个有 4 列的实体类,所以我的数据库也只有 4 列。但是在编写我的 HQL 时,我正在使用生成 5 列的自定义 SQL 查询。距离场是动态生成的。

@Entity
public class Entity {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String latitude;
    private String longitude;
    @Transient
    private double distance;
}

现在执行例如查询,如下 -

String q= "Select id, name, latitude, longitude, (latitude - 1) as distance from Entity";
        SQLQuery query = s.createSQLQuery(q);
        query.addEntity(Entity.class);
        List<Entity> results = query.list();

所有其他列都映射到实体对象,但我的距离字段没有被映射。我将距离注释为瞬态,因为我不希望我的数据库中的列,但由于字段是瞬态的,它在 HQL 实体对象中也被忽略了。 请帮我解决一下这个。如何做到这一点?

【问题讨论】:

  • 呃,经度,纬度为字符串。
  • @neilstockton 哈哈,所有这些都只是一个示例问题。这样你也会讨厌类名和公式:p

标签: java hibernate jpa hql transient


【解决方案1】:

有两种可能的解决方案。在您的情况下,最好使用 @Formula annotation 声明计算字段。使用此注解,您可以指定 SQL 片段而不是将属性映射到列:

@Entity
public class Entity {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String latitude;
    private String longitude;

    @Formula(latitude - 1)
    private double distance;
}

现在您可以使用序号正常 HQL 请求获取实体,并且将计算字段。但请注意,此解决方案仅在您使用 HQL 时有效,而在 JPA 中无效,因为 JPA 不支持 @Formula

在 JPA 中最好使用 @PostLoad annotation:

@Entity
public class Entity {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String latitude;
    private String longitude;

    @Transient
    private double distance;

    @PostLoad 
    public void postLoad(){
        distance = latitude - 1;
    }
}

然后你就可以用普通的 JPQL 来获取这个实体了。

【讨论】:

  • 正是我想要的。谢谢!能否也告诉我在Formula或PostLoad的情况下,如何使用外部参数传入查询?
  • 很遗憾,您不能将动态参数传递给@Formula。从@PostLoad,您可以从之前存储它的Java 变量中读取参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多