Hibernate映射文件中的formula应用

导读:本篇文章讲解 Hibernate映射文件中的formula应用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

hibernate映射文件中的property中可以用formula属性来实现该字段的值不存入数据库,而通过sql的运算函数来运算获取。如:下面的年龄,在表中并不存在,而是通过出生日期来计算获得

实体类 Student
 

@Data
public class Student {
	private int id;
	private String name;
	private Date birthday;
	private int age;

}

映射文件 Student.hbm.xml
 

<hibernate-mapping>
    <class name="com.restfullDemo.model.Student" table="students">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="birthday" />
        </property>
        <property name="age" type="int"
        formula="(SELECT FLOOR(DATEDIFF(NOW(),s.birthday)/365.25) FROM students s where s.id=id)"
        >
           
        </property>
    </class>
</hibernate-mapping>

测试:
 

//先存入一个Student对象,并没有设置age值 
public void saveStudent() throws ParseException {
		Session session = SessionFactory.getSession();
		Student st=new Student();
		st.setName("lish");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date dt=sdf.parse("2001-05-10");
		st.setBirthday(dt);
		session.save(st);
		session.close();
		
	}


//获取对象时通过运算,则返回了age的值
public void gettudent() throws ParseException {
		Session session = SessionFactory.getSession();
		Student st=session.get(Student.class, 1);
		System.out.println(st.getAge());
		session.close();
		
	}

其它参考:

Property元素中的formula允许对象属性包含导出值,比如sum、average、max等的结果。如:

<property name=”averagePrice” formula=”(select avg(pc.price) from PriceCatalogue pc, SelectedItems si where si.priceRefID=pc.priceID)”/>  
 

此外,formula还可以基于当前记录的特定属性值从另一个表检索值。例如:

代码
<property name=”currencyName” formula=”(select cur.name from currency cur where cur.id= currencyID)”/>  
 

代码
<property name=”schNum” formula=”(select max(a.schoolNumb) from sys_act_code as a)”/>  
注意:
1,formula=”()”,里面的是sql语句,字段和表名都应该和数据库相应,而不是字段,若带有参数如cur.id= currencyID,这个currencyID才是对象的东东.
2,formula=”( sql )”,这个括号不能少,不然会报错,我试了几次,没括号就报错,添上就没问题
3,操作字段一定要用别名

问题:
 1,org.springframework.orm.hibernate3.HibernateSystemException: Null value was assigned to a property of primitive type setter of
没用别名,会出现这个错误,添个别名就好了

2,如果我要用obj.getSchNum()得到想要的值,该对象(obj)必须是hibernate取得的对象,

3,如果要传入参数,如上面那个,currencyID是该对象的属性,它的值也是有hibernate操作当前对象时,把该属性对应的值自动传入进去.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/71210.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!