`

hibernate学习2之many-to-one

阅读更多
public class Group {
	private int id;
	private String name;
	//setter,getter
}

public class User {
	private int id;
	private String name;
	private Group group;//多个用户对应一个组
       //setter,getter
}

Group.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.bjsxt.hibernate.Group" table="t_group">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name"/>
	</class>
</hibernate-mapping>

User.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.bjsxt.hibernate.User" table="t_user">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name"/>
		<many-to-one name="group" column="groupid" cascade="all"/>
	</class>
</hibernate-mapping>

hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_many2one</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">bjsxt</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.show_sql">true</property>
		
		<mapping resource="com/bjsxt/hibernate/User.hbm.xml"/>
		<mapping resource="com/bjsxt/hibernate/Group.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

测试一下:
public void testSave() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			Group group = new Group();
			group.setName("尚学堂");
			
			User user1 = new User();
			user1.setName("菜10");
			user1.setGroup(group);
			
			User user2 = new User();
			user2.setName("容祖儿");
			user2.setGroup(group);
			
			//不会抛出异常,因为User.hbm.xml中采用了cascade(级联)属性,它会在保存User前先保存Group(这样就用不着显式的调用session.save(group);)
			//采用cascade属性是解决TransientObjectException异常的一种手段			
			session.save(user1);
			session.save(user2);
			session.getTransaction().commit();
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}	
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics