hibernate映射文件的formula简单使用

xiaoxiao2024-10-27  17

以前没有用过formula,今天试了试,

还是用学生和书本这个one-to-many关系来说明吧:

Students.hbm.xml:

<hibernate-mapping> <class table="T_Students" name="com.hewill.model.Students"> <id type="java.lang.String" column="id" length="32" name="id"> <generator class="uuid.hex"/> </id> <property name="bookCount" formula="(select count(*) from T_Books )"/> <property name="name" type="java.lang.String" column="name"/> <property name="sex" type="java.lang.String" column="sex"/> <property name="number" type="java.lang.String" column="number"/> <set inverse="true" cascade="all" name="books"> <key column="student_id"/> <one-to-many class="com.hewill.model.Books"/> </set> </class> </hibernate-mapping>

 

Books.hbm.xml:

<hibernate-mapping> <class table="T_Books" name="com.hewill.model.Books"> <id type="java.lang.String" column="id" length="32" name="id"> <generator class="uuid.hex"/> </id> <property name="bookname" type="java.lang.String" column="bookname"/> <many-to-one column="student_id" name="studentid" class="com.hewill.model.Students"/> </class> </hibernate-mapping>

  

测试代码:

public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); Query query = session.createQuery("from Students where name='liu'"); List<Students> list = query.list(); for(Students students : list){ System.out.println("name : "+students.getName()); System.out.println("number : "+students.getNumber()); System.out.println("bookCount : "+students.getBookCount()); } tx.commit(); session.close(); }

 

结果:

Hibernate: select students0_.id as id0_, students0_.name as name0_, students0_.sex as sex0_, students0_.number as number0_, (select count(*) from T_Books ) as formula0_ from T_Students students0_ where students0_.name='liu' name : liu number : 006 bookCount : 2

 

从hibernate执行的语句中,我们可以看到Students的bookCount属性是formula通过执行指定的“select count(*) from T_Books ”来获得的。bookCount字段在数据库T_Students表中是没有的,它是一个虚拟列。像这样,当我们需要用数据库来完成一些计算,并想获得这个计算结果时,完全可以用formula.

formula的使用注意事项网上很多,就不在提了。

转载请注明原文地址: https://www.6miu.com/read-5018646.html

最新回复(0)