一、假定一个人只有多个地址,一个地址只对应一个人,那么人和地址对应关系为1对多。
二、
1、添加依赖包,参考上篇文章hibernate+mysql入门使用
2、初始化数据库
DROP DATABASE IF EXISTS moy_hibernate; CREATE DATABASE moy_hibernate CHARACTER SET UTF8;
3、新建实体类Address和Person
package com.moy.hibernate4.entity; import org.hibernate.annotations.Cascade; import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * [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 = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int addressId; private String addressDetail; @ManyToOne(targetEntity = Person.class) @JoinColumn(name = "person_id", referencedColumnName = "id", nullable = false) private Person person; 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; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @Override public String toString() { return "Address{" + "addressId=" + addressId + ", addressDetail='" + addressDetail + ''' + ", person=" + person + '}'; } }
package com.moy.hibernate4.entity; import org.hibernate.annotations.Cascade; import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * [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 = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int addressId; private String addressDetail; @ManyToOne(targetEntity = Person.class) @JoinColumn(name = "person_id", referencedColumnName = "id", nullable = false) private Person person; 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; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @Override public String toString() { return "Address{" + "addressId=" + addressId + ", addressDetail='" + addressDetail + ''' + ", person=" + person + '}'; } }
4、新建配置文件hibernate.cfg.xml和log4j.xml
<?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>
<?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
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测试
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() { Person firstPerson = new Person(); firstPerson.setName("测试1对多"); firstPerson.setAge(233); session.persist(firstPerson); Address firstAddress = new Address(); firstAddress.setAddressDetail(firstAddress.toString()); firstAddress.setPerson(firstPerson); session.persist(firstAddress); Address secondAddress = new Address(); secondAddress.setAddressDetail(secondAddress.toString()); secondAddress.setPerson(firstPerson); session.persist(secondAddress); } }
yexiangyang
moyyexy@gmail.com