框架:Hibernate单向一对多
一、假定一个人只有多个地址,一个地址只对应一个人,那么人和地址对应关系为1对多。
二、
1、添加依赖包,参考上篇文章hibernate+mysql入门使用
2、初始化数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
DROP DATABASE IF EXISTS moy_hibernate;
CREATE DATABASE moy_hibernate CHARACTER SET UTF8;
3、新建实体类Address和Person
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.moy.hibernate4.entity; import javax.persistence.*; /** * [Project]:moy-gradle-project <br/> * [Email]:moy25@foxmail.com <br/> * [Date]:2018/2/25 <br/> * [Description]: <br/> * * @author YeXiangYang */ @Entity @Table(name = "t_address") public class Address { @Id @Column(name = "address_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int addressId; private String addressDetail; public int getAddressId() { return addressId; } public void setAddressId(int addressId) { this.addressId = addressId; } public String getAddressDetail() { return addressDetail; } public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } @Override public String toString() { return "Address{" + "addressId=" + addressId + ", addressDetail='" + addressDetail + '\'' + '}'; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.moy.hibernate4.entity; import javax.persistence.*; import java.util.HashSet; import java.util.Set; /** * [Project]:moy-gradle-project <br/> * [Email]:moy25@foxmail.com <br/> * [Date]:2018/2/25 <br/> * [Description]: <br/> * * @author YeXiangYang */ @Table(name = "t_person") @Entity public class Person { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private int age; @OneToMany(targetEntity = Address.class, cascade = CascadeType.ALL) @JoinColumn(name = "ref_person_Id", referencedColumnName = "id") private Set<Address> address = new HashSet<>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Set<Address> getAddress() { return address; } public void setAddress(Set<Address> address) { this.address = address; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", address=" + address + '}'; } }
4、新建配置文件hibernate.cfg.xml和log4j.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 指定连接数据库所用的驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 --> <property name="connection.url">jdbc:mysql://localhost:3306/moy_hibernate</property> <!-- 指定连接数据库的用户名 --> <property name="connection.username">root</property> <!-- 指定连接数据库的密码 --> <property name="connection.password">123</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 根据需要自动创建数据表 --> <property name="hbm2ddl.auto">update</property> <!-- 显示Hibernate持久化操作所生成的SQL --> <property name="show_sql">true</property> <!-- 将SQL脚本进行格式化后再输出 --> <!--<property name="hibernate.format_sql">true</property>--> <!-- 罗列所有持久化类的类名 --> <mapping class="com.moy.hibernate4.entity.Person"></mapping> <mapping class="com.moy.hibernate4.entity.Address"></mapping> </session-factory> </hibernate-configuration>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p %-5c{3}\:%L %x %n-> %m%n"/> </layout> </appender> <root> <priority value="DEBUG"/> <appender-ref ref="console"/> </root> </log4j:configuration>
5、为了方便测试,编写一个获取Session的工具类Hibernate4Utils
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.moy.hibernate4.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import java.util.Objects; public abstract class Hibernate4Utils { static { try { Configuration conf = new Configuration().configure(); ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sessionFactory = conf.buildSessionFactory(registry); } catch (Throwable e) { throw e; } } public static final SessionFactory sessionFactory; public static final ThreadLocal<Session> sessionThread = new ThreadLocal<>(); /** * 获取当前线程安全Session */ public static Session getCurrentSession() { Session session = sessionThread.get(); if (Objects.isNull(session)) { session = sessionFactory.openSession(); sessionThread.set(session); } return session; } /** * 关闭Session */ public static void closeCurrentSession() { Session session = sessionThread.get(); if (Objects.nonNull(session)) { session.close(); } sessionThread.set(null); } }
6、新建测试类OneToManyTest测试
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.moy.hibernate4.entity; import com.moy.hibernate4.util.Hibernate4Utils; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * [Project]:moy-gradle-project <br/> * [Email]:moy25@foxmail.com <br/> * [Date]:2018/2/25 <br/> * [Description]: <br/> * * @author YeXiangYang */ public class OneToManyTest { Session session; Transaction transaction; @Before public void before() { session = Hibernate4Utils.getCurrentSession(); transaction = session.beginTransaction(); } @After public void after() { transaction.commit(); Hibernate4Utils.closeCurrentSession(); } @Test public void test() { Address firstAddress = new Address(); firstAddress.setAddressDetail(firstAddress.toString()); session.persist(firstAddress); Address secondAddress= new Address(); secondAddress.setAddressDetail(secondAddress.toString()); session.persist(secondAddress); Person p = new Person(); p.setName("测试1对多"); p.setAge(233); p.getAddress().add(firstAddress); p.getAddress().add(secondAddress); session.persist(p); } }
yexiangyang
moyyexy@gmail.com