zoukankan      html  css  js  c++  java
  • Hibernate设置派生属性(formula)

    一、Customer中包含的字段:

    private static final long serialVersionUID = 1L;
        private Integer id;
        private String sex;
        private double salary;
        private Double comm;
        private String birth;
        private Double total;
        private String desc;

    二、Hibernate配置文件

    <class name="Customer" table="customers" catalog="hjd">
            <id name="id" column="id">
                <generator class="native"></generator>
            </id>
            <property name="sex" length="4"></property>
            <property name="salary" />
            <property name="comm"/>
            <!-- 类中没有birth的get set 方法 -->
            <property name="birth" type="date" access="field"/>
            
            <!-- 映射Java持久化类中不存在的属性,只要用于HQL中,当数据库中有某列,二实体中不存在 -->
            <property name="deptName" type="string" access="noop"/>
            
            <property name="total" formula="(select c.salary+c.comm from customers c where c.id=id)"></property>
            <property name="desc" column="`desc`"/>
        </class>

    三、测试

    获得每个部门发出的工资总数

    @Test
        public void getObject() {
            Session session = HiberSessionFactory.getSession();
            /*Customer c=(Customer) session.get(Customer.class, 2);
            System.out.println(c.getTotal());*/
            @SuppressWarnings("unchecked")
            List<Customer> list=session.createCriteria(Customer.class).add(Restrictions.eq("deptName", "军")).list();
            int total=0;
            for(Customer c:list){
                total+=c.getTotal();
            }
            System.out.println(total);
            HiberSessionFactory.closeSession();
        }

  • 相关阅读:
    Redis基础用法
    SpringCloud
    Excel数据导入数据库
    MySQL数据库汇总
    Java8stream表达式
    LocalDateTime&LocalDate&LocalTime
    深入理解Java中的锁
    数据集合
    平台介绍
    dubbo源码阅读之自适应扩展
  • 原文地址:https://www.cnblogs.com/ly-radiata/p/4462535.html
Copyright © 2011-2022 走看看