多个address对应一个user
1.address.java
public class Address {
private Long id;
private String name;
private User user;
//省略了getters/setters/constructs/toString
}
address.hbm.xml
<hibernate-mapping>
<!--
name:类名
table:表名
-->
<class name="com.qfedu.entity.Address" table="address">
<!-- 主键 -->
<id name="id" column="id">
<generator class="native"></generator>
</id>
<!-- 其他属性 -->
<property name="name" column="name"></property>
<!--定义多对一-->
<many-to-one name="user" class="com.qfedu.entity.User" column="user_id"></many-to-one>
</class>
</hibernate-mapping>
2.user.java
public class User {
private Long id;
private String name;
private int age;
//省略了getters/setters/constructs/toString
}
user.hbm.xml
<hibernate-mapping>
<!--
name:类名
table:表名
-->
<class name="com.qfedu.entity.User" table="user">
<!-- 主键 -->
<id name="id" column="id">
<generator class="native"></generator>
</id>
<!-- 其他属性 -->
<property name="name" column="name"></property>
<property name="age" column="age"></property>
</class>
</hibernate-mapping>
3.测试:
public static void main( String[] args )
{
//1.创建sessionFactory对象
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//2.创建session对象
Session session= sessionFactory.openSession();
//3.开启事务
Transaction tx = session.beginTransaction();
//4.执行
User u = new User();
u.setName("zhangsan1");
u.setAge(18);
Address ad1= new Address();
ad1.setName("beijing");
ad1.setUser(u);
Address ad2= new Address();
ad2.setName("qingdao");
ad2.setUser(u);
session.save(ad1);
session.save(ad2);
session.save(u);
//5.提交事务
tx.commit();
//6.关闭session
session.close();
sessionFactory.close();
}