0

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

测试类

        @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;
4

1 回答 1

1

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

请参阅此线程以获取两种解决方案:

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"
)})
于 2015-08-14T15:22:16.147 回答