- Hibernate 中formula标签和query标签的使用
- 有两张表 主外键关系
- CREATE TABLE `catg` (
- `id` int(11) NOT NULL auto_increment,
- `cname` varchar(50) default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- CREATE TABLE `cgoods` (
- `id` int(11) NOT NULL auto_increment,
- `gname` varchar(11) default NULL,
- `gdes` varchar(50) default NULL,
- `cid` int(11) default NULL,
- PRIMARY KEY (`id`),
- KEY `FK_cid` (`cid`),
- CONSTRAINT `FK_cid` FOREIGN KEY (`cid`) REFERENCES `catg` (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- Cgoods.xml:
- <hibernate-mapping package="com.vo">
- <class name="Cgoods" table="cgoods">
- <id name="id" column="id" type="int">
- <generator class="native"></generator>
- </id>
- <property name="gname" column="gname" type="string"/>
- <property name="gdes" column="gdes" type="string"/>
- <many-to-one name="catg" column="cid" class="Catg" cascade="save-update">
- </many-to-one>
- </class>
- </hibernate-mapping>
- Catg.xml:
- <hibernate-mapping package="com.vo">
- <class name="Catg" table="catg">
- <id name="id" column="id" type="int">
- <generator class="native"></generator>
- </id>
- <property name="cname" column="cname" type="string">
- </property>
- <property name="count"> //增加一个属性取出该类别在子表中的个数
- <formula>
- (select count(p.id) from Cgoods p where p.cid=id group by p.cid)
- </formula>
- </property>
- </class>
- <query name="CatgQuery">from Catg c</query>
- </hibernate-mapping>
- Test.java:
- Configuration config=new Configuration().configure();
- SessionFactory sf= config.buildSessionFactory();
- Session se=sf.openSession();
- Query query = se.getNamedQuery("CatgQuery");
- List list= query.list();
- //System.out.println(list.size());
- Iterator iter= list.iterator();
- while(iter.hasNext()){
- Catg temp=(Catg)iter.next();
- System.out.println(temp.getId() + ":" + temp.getCname()
- +","+temp.getCount());
- }
Hibernate 中formula标签和query标签的使用
最新推荐文章于 2021-05-20 19:19:05 发布