Hibernate02_一对多
客户可以有多个订单,但每个订单只能属于一个客户。
客户为一,订单为多。
客户为主表,订单为从表。通过主外键关系来维护。
orders表
package com.blu.entity;
import java.util.Set;
import lombok.Data;
@Data
public class Customer {
private Integer id;
private String name;
private Set<Orders> orders;
}
package com.blu.entity;
import lombok.Data;
@Data
public class Orders {
private Integer id;
private String name;
private Customer customer;
}
<?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>
<class name="com.blu.entity.Customer" table="customer">
<id name="id" type="java.lang.Integer">
<column name="id"></column>
<generator class="identity"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="name"></column>
</property>
<set name="orders" table="orders" lazy="true">
<key column="cid"></key>
<one-to-many class="com.blu.entity.Orders"></one-to-many>
</set>
</class>
</hibernate-mapping>
<?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.blu.entity">
<class name="Orders" table="orders">
<id name="id" type="java.lang.Integer">
<column name="id"></column>
<generator class="identity"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="name"></column>
</property>
<many-to-one name="customer" class="Customer" column="cid"></many-to-one>
</class>
</hibernate-mapping>
注:在 hibernate-mapping 标签上统一指定了实体类的包名 package=“com.blu.entity” ,class的name属性和many-to-one的class属性就可以简写啦!
<mapping resource="com/blu/entity/Customer.hbm.xml"></mapping>
<mapping resource="com/blu/entity/Orders.hbm.xml"></mapping>
package com.blu.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.blu.entity.Customer;
import com.blu.entity.Orders;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Customer customer = new Customer();
customer.setName("张三");
Orders orders = new Orders();
orders.setName("订单1");
orders.setCustomer(customer);
session.save(customer);
session.save(orders);
session.beginTransaction().commit();
session.close();
}
}
Hibernate:
insert
into
customer
(name)
values
(?)
Hibernate:
insert
into
orders
(name, cid)
values
(?, ?)
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blucoding.blog.csdn.net/article/details/107773988
内容来源于网络,如有侵权,请联系作者删除!