【问题标题】:Add Case Statement in hibernate在hibernate中添加case语句
【发布时间】:2017-11-08 08:17:55
【问题描述】:

我正在创建 API,它以JSON 格式向客户端发送响应。 我在做什么,我在Mysql DB 中有一个表,其中有一个主键。客户端使用该主键作为参数请求数据,我使用hibernate 从数据库中获取数据并作为响应发送回客户端。

我的 SQL 查询:

select * from emp_table Where id = 202

在 JSON 响应中,我将发送表的所有列,如上述查询中所示。到这里我的代码工作正常。

但现在我正在使用case statement 生成一个新列,如以下查询所示:

select *, (case when sal > 4.5  then 'Yes' else 'No' end)  as bp_status from emp_table Where id = 202

如何在JSON 响应中发送这个新的bp_status 列??

我尝试使用 @Formula 但无法正常工作

@Formula(value = "(case when sal > 4.5  then 'Yes' else 'No' end)")
private String bp_status; 

【问题讨论】:

    标签: hibernate jakarta-ee hibernate-annotations


    【解决方案1】:

    由于sal 列在您的emp_table 中,因此您的Employee 实体具有sal 属性,并且您的实体看起来像

    @Entity
    public class Employee{
    
        @Column(name = "sal")
        private Double sal;
    
    }
    

    那么使用加载实体后加载的瞬态属性怎么样?

    import javax.persistence.Transient;
    import javax.persistence.PostLoad;
    
    @Entity
    public class Employee{
    
        @Column(name = "sal")
        private Double sal;
    
        // define here as an attribute so that you can do
        // whatever you want in your JSON process
        @Transient
        private String bpStatus;
    
        public Employee(){
            // ...
    
            // initialise an empty value to avoid a NullPointerException
            // when processing your JSON
            this.bpStatus = "";
        }
    
        // Tell JPA to add additional stuff after loading the entity
        @PostLoad
        public void postLoad(){
            // simplified version: you must ensure that
            // sal is not null and stuff like that
            this.bpStatus = (sal > 4.5) ? "Yes" : "No";
        }
    
    }
    

    重写后加载方法时要小心:根据我的实验,您只需要 @Override 注释,并且不应将重写的方法注释为 @PostLoad,因为 JPA 会找到两个后加载方法,即使签名是一样的。

    【讨论】:

    • 嗨Al1,谢谢我尝试了上面的代码,我在Json 响应中得到了bpStatus,但是每次我得到bpStatus 的默认值,它是空白的,而不是Yes 或@ 987654335@,我的sal栏不为空
    • @PostLoad 仅由 JPA 调用:您的实体是否由实体管理器获取?在这个阶段,我通常只放一个System.out.print... 以确保调用我的后加载方法。否则,一个肮脏的技巧是在调用 JSON 方法之前设置 bpStatus 值,但这会破坏 JPA 设计的美感:(
    • 嗨,AI,我正在使用基于 SessionFactory 的配置 sessionFactory = HibernateUtility.getSessionFactory(); session_hiber = sessionFactory.openSession(); session_hiber.beginTransaction(); 是这个问题吗??
    • 老实说,我不知道,我是 EclipseLink 和 EntityManager 用户。根据this questionHibernateUtility 不是 JPA 标准,因此永远不会调用 @PostLoad。这里建议One solution。看起来 Hibernate 有一个 @PostLoad via the Lifecycle's onLoad()
    • @ansh 你找到合适的解决方案了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多