Hibernate ORM 之 单向一对多
单向一对多:一方持有多方的集合。
在一方持有多方的集合上使用@OneToMany和@JoinColumn注解
1 pom.xml
<project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >
<modelVersion > 4.0.0</modelVersion >
<groupId > com.libill</groupId >
<artifactId > hibernate-demo</artifactId >
<packaging > war</packaging >
<version > 1.0-SNAPSHOT</version >
<name > hibernate-demo Maven Webapp</name >
<url > http://maven.apache.org</url >
<dependencies >
<dependency >
<groupId > org.hibernate</groupId >
<artifactId > hibernate-core</artifactId >
<version > 5.2.10.Final</version >
</dependency >
<dependency >
<groupId > mysql</groupId >
<artifactId > mysql-connector-java</artifactId >
<version > 5.1.38</version >
</dependency >
<dependency >
<groupId > junit</groupId >
<artifactId > junit</artifactId >
<version > 4.12</version >
</dependency >
</dependencies >
<build >
<finalName > hibernate-demo</finalName >
</build >
</project >
2 hibernate.cfg.xml配置文件
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration >
<session-factory >
<property name ="connection.url" > jdbc:mysql://192.168.145.128:3306/hibernate?useUnicode=true&characterEncoding=utf-8</property >
<property name ="connection.driver_class" > com.mysql.jdbc.Driver</property >
<property name ="connection.username" > root</property >
<property name ="connection.password" > 123456</property >
<property name ="connection.autocommit" > false</property >
<property name ="hbm2ddl.auto" > update</property >
<property name ="show_sql" > true</property >
<property name ="format_sql" > true</property >
<property name ="dialect" > org.hibernate.dialect.MySQL55Dialect</property >
<mapping class ="com.libill.beans.Customer" />
<mapping class ="com.libill.beans.Order" />
</session-factory >
</hibernate-configuration >
3 实体类
package com.libill.beans;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table (name = "t_customer" )
@SuppressWarnings (value = {"unused" })
public class Customer {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String phone;
@OneToMany (fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn (name = "cid" , foreignKey = @ForeignKey (name = "fk_c_o" ))
private Set<Order> orders = new HashSet<Order>();
public Customer () {
}
public Customer (String name, String phone) {
this .name = name;
this .phone = phone;
}
public int getId () {
return id;
}
public void setId (int id) {
this .id = id;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public String getPhone () {
return phone;
}
public void setPhone (String phone) {
this .phone = phone;
}
public Set<Order> getOrders () {
return orders;
}
public void setOrders (Set<Order> orders) {
this .orders = orders;
}
}
package com.libill.beans;
import com.sun.istack.internal.Nullable;
import javax.persistence.*;
@Entity
@Table (name = "t_order" )
@SuppressWarnings (value = {"unused" })
public class Order {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private int id;
private String content;
public Order () {
}
public Order (String content) {
this .content = content;
}
public int getId () {
return id;
}
public void setId (int id) {
this .id = id;
}
public String getContent () {
return content;
}
public void setContent (String content) {
this .content = content;
}
}
4 测试类
package com.libill.beans;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.EnumSet;
@SuppressWarnings (value = {"unused" })
public class BeansTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
private SchemaExport schemaExport;
@Before
public void init () {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void destroy () {
transaction.commit();
session.close();
sessionFactory.close();
}
/**
* 测试实体对象的保存
*/
@Test
public void saveTest () {
Customer customer = new Customer("张三" , "13982502467" );
Order order = new Order("馒头" );
customer.getOrders().add(order);
session.save(customer);
}
/**
* 测试根据实体对象生成数据库表,只创建表
*/
@Test
public void testSchema () {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
SchemaExport schemaExport = new SchemaExport();
schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);
}
}
5 结果