Hibernate HQL

两个蝴蝶飞 2013-02-07

本人想通过该篇文章介绍下如何使用Hibernate HQL语句,基本上SQL语句的查询都能在HQL中找到对

应的实现。

创建了几个表,这几个表是用于HQL演示用。t_user是一个单独的表,没有与其他表进行关联。

company和employee这两个表有一个一对多的关联关系

user和role是一个多对多的关联关系,中间表为user_role

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

CREATE TABLE `company` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `company_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK4AFD4ACE19AF9E2B` (`company_id`),
  CONSTRAINT `FK4AFD4ACE19AF9E2B` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

CREATE TABLE `role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

CREATE TABLE `user_role` (
  `userId` int(11) DEFAULT NULL,
  `roleId` int(11) DEFAULT NULL,
  KEY `FK143BF46AF9C1C096` (`roleId`),
  KEY `FK143BF46AFF171600` (`userId`),
  CONSTRAINT `FK143BF46AF9C1C096` FOREIGN KEY (`roleId`) REFERENCES `role` (`id`),
  CONSTRAINT `FK143BF46AFF171600` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

对应的Hibernate映射文件

Person.hbm.xml

<hibernate-mapping package="com.guchao.hibernate.entity">
	<class name="Person" table="t_user">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name" column="username" type="string"></property>
		<property name="age" column="age" type="integer"></property>
		<property name="birthday" column="birthday" type="date"></property>
	</class>

</hibernate-mapping>
 

相关推荐