尝试在休眠中使用 SQL 函数

Trying to use SQL Function in hibernate

我正在尝试调用 My-SQL 函数,该函数返回基于输入参数的计算值。为此,我正在使用本机查询,我能够获取除计算字段之外的所有字段。我总是将 NULL 作为计算字段的值。此外,如果我在 SQL 客户端中执行相同的查询,它会给出正确的结果。

Test.class

        @NamedNativeQueries({
        @NamedNativeQuery(
        name = "getTestData", 
        query = "Select test_id, BillType, Description, Material, Netvalue1, "
              + "NetValue(billType, Netvalue1) as Sales_Rs "
              + "from test1",
        resultClass = Test.class
        )
    })

    @Entity
    @Table(name="TEST1")
    public class Test {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue
        @Column(name="TEST_ID")
        private Integer test_id;

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

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

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

        @Column(name="Netvalue1")
        private Double Netvalue1;

        @Transient
        private Double Sales_Rs; 
// getters and setters 
.
.
.
};

以下是我调用本机查询的方式:

@SuppressWarnings("unchecked")
    @Override
    public List<Test> getAllTestData() throws MyAppException {
        List<Test> result;

        try {
            Session session = sessionFactory.getCurrentSession();

            Query query = session.getNamedQuery("getTestData");

            result = query.list();

        } catch (DataAccessException e) {
            throw new MyAppException("Could not add a new record :", e);
        }

        return result;
    }

这里是存储函数:

CREATE FUNCTION NetValue(billType CHAR(30), Netvalue1 DOUBLE) RETURNS double
BEGIN
    Declare RetValue DOUBLE;

  SET RetValue =
  CASE billType 
    WHEN 'A' THEN 0.10 * Netvalue1
    WHEN 'B' THEN 0.05 * Netvalue1
    WHEN 'C' THEN 0.025 * Netvalue1
    ELSE Netvalue1
  END;

    RETURN RetValue;
END;

您将字段 Double Sales_Rs 声明为瞬态,因此 Hibernate 不处理它。

this thread两种解决方案:

a) 使用特定于 Hibernate 的映射通过调用数据库函数的公式计算 Sales_RS

@Formula("NetValue(billType, Netvalue1)")
private Double Sales_Rs; 

b) 使用JPA @Postload注解在对象加载后计算Sales_RS

@Transient
private Double Sales_Rs;

@PostLoad
private void onLoad() {
     Sales_Rs = ... //  same logic as in your db function
}

在这两种情况下,您都可以放弃本机查询并使用简单的 hql:

@NamedQueries({
    @NamedQuery(
       name  = "getTestData",
       query = "from Test"
)})