Role.java
package com.hw.dao;
import java.io.Serializable;
import java.util.Set;
public class Role implements Serializable {
private int rid ;
private String name;
private Set<Users> users;
//get set 方法
}
Role.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hw.dao">
<class name="Role" table="ROLE">
<id name="rid">
<column name="RID"></column>
</id>
<property name="name">
<column name="NAME"></column>
</property>
<set name="users" cascade="all">
<key>
<column name="RID"></column>
</key>
<one-to-many class="Users"/>
</set>
</class>
</hibernate-mapping>
Users.java
import java.io.Serializable;
public class Users implements Serializable{
private int id;
private String username;
private String password;
private Role role; //★
//get set 方法
}
Users.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hw.dao">
<class name="Users" >
<id name="id">
<column name="ID"></column>
</id>
<property name="username">
<column name="USERNAME"></column>
</property>
<property name="password">
<column name="PASSWORD"></column>
</property>
<many-to-one name="role" class="Role" >
<column name="RID"></column>
</many-to-one>
</class>
</hibernate-mapping>
测试类
public class test {
public static void main(String[] args) {
Configuration cf = new Configuration().configure();
SessionFactory sf=cf.buildSessionFactory();
Session s=sf.openSession();
/**
s.beginTransaction();
Role role= new Role();
role.setRid(1);
role.setName("admins");
Set<Users> set= new HashSet<Users>();
Users user= new Users();
user.setId(1);
user.setUsername("jack");
user.setPassword("123");
set.add(user);
Users user1= new Users();
user1.setId(2);
user1.setUsername("jacks");
user1.setPassword("456");
set.add(user1);
role.setUsers(set);
s.save(role);
s.getTransaction().commit();*/
/**
String hql="from Role";
Query query=s.createQuery(hql);
List<Role> list=query.list();
for (Role role : list) {
System.out.println(role.getRid()+ " "+role.getName());
Set<Users> set =role.getUsers();
for (Users user : set) {
System.out.println(user.getId()+" "+user.getUsername()+" "+ user.getPassword()+" "+user.getRole().getRid());
}
}*/
String hql="from Users";
Query query= s.createQuery(hql);
List<Users> list=query.list();
for (Users user : list) {
System.out.println(user.getId()+" "+ user.getUsername()+" "+ user.getPassword() +" "+ user.getRole().getRid()+" "+ user.getRole().getName());
}
}
}