hibernate one-to-many

同样的,班级和学生是一对多的关系,
目标,查询班级的时候,希望查询出班级学生列表!!

GradeClass.java  POJO代码
public class GradeClass {

	private Long gradeClassId;
	private String gradeClassName;
	private Set<User> users = new HashSet<User>();
         //...省略get和set方法
}



GradeClass.hbm.xml代码
<hibernate-mapping>
		<class name="com.supben.pojo.GradeClass" table="gradeclass">
				<id name="gradeClassId" type="java.lang.Long">
						<column length="20" name="gradeClassId" />
						<generator class="identity"></generator>
				</id>

				<property name="gradeClassName" type="java.lang.String">
						<column name="gradeClassName" />
				</property>
  <!--column="gradeClassId"指的是user(class属性指定)表中的gradeClassId字段 -->
				<set name="users" lazy="false" fetch="join">
						<key column="gradeClassId" />
						<one-to-many class="com.supben.pojo.User" />
				</set>

		</class>
</hibernate-mapping>


user.hbm.xml: 和平时配置没有任何的不同
<hibernate-mapping>
		<class name="com.supben.pojo.User" table="User">
				<id name="userId" type="java.lang.Long">
						<column length="20" name="userId" />
						<generator class="identity"></generator>
				</id>

				<property name="userName" type="java.lang.String">
						<column name="userName" />
				</property>
		</class>
</hibernate-mapping>




测试代码
public void testFind() {
		List<GradeClass> classList = gradeClassService.findAll();
		System.out.println("*************************************");
		Set<User> users = classList.get(0).getUsers();

		for (User user : users) {
			System.out.println(user.getUserName());
		}
	}





运行结果:

Hibernate: select this_.gradeClassId as gradeCla1_0_1_, this_.gradeClassName as gradeCla2_0_1_, users2_.gradeClassId as gradeCla3_3_, users2_.userId as userId3_, users2_.userId as userId1_0_, users2_.userName as userName1_0_, users2_.gradeClassId as gradeCla3_1_0_ from gradeclass this_ left outer join User users2_ on this_.gradeClassId=users2_.gradeClassId
*************************************
chenglong
supben


注:GradeClass.hbm.xml中set里面的column="gradeClassId",对应的是user表里面的字段。 如同many-to-one一样,one-to-many默认的也是lazy="true" fetch="select"。(见前面一篇)。所以可以酌情配置成lazy="false" fetch="join"

你可能感兴趣的:(xml,Hibernate)