Hibernate02_一对多

x33g5p2x  于2021-12-25 转载在 其他  
字(3.1k)|赞(0)|评价(0)|浏览(283)

Hibernate02_一对多

一对多关系

客户可以有多个订单,但每个订单只能属于一个客户。
客户为一,订单为多。
客户为主表,订单为从表。通过主外键关系来维护。

  • 数据表
    customer表

orders表

  • 在实体类中:
  • Customer
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;
}
  • Orders
package com.blu.entity;

import lombok.Data;

@Data
public class Orders {
	private Integer id;
	private String name;
	private Customer customer;
}
  • Customer.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>
	<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>
  • Orders.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.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
        (?, ?)

相关文章