1、一多对,就是多对一的反方向,既一个公司可以对应多个人。多个人对应一个公司。两者的关系是双休的。
所以Person类与Company类的代码如下所示:
package com.mr.cheng.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.Cascade;
@Entity
public class Person {
private Integer id;
private String name;
private int age;
private double price;
/**
* 单项
* 多对一配置 外键
* cascade 是否保存一方
* fetch 是否立即查询一的一方
*/
private Company company;
/**
* 注意在类中注解要么在字段上,要么在getter方法上,不能一个在getter上另外一个在字段上,
* @return
*/
@ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
@JoinColumn(name="companyId")
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age
+ ", price=" + price + ", company=" + company + "]";
}
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
package com.mr.cheng.entity;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
@Entity
public class Company {
@Override
public String toString() {
return "Company [id=" + id + ", name=" + name + "]";
}
private int id;
private String name;
private Set<Person>persons;
@OneToMany(fetch= FetchType.LAZY)
@JoinColumn(name="companyId")
public Set<Person> getPersons() {
return persons;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
@Id
@GeneratedValue
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;
}
}
2、 hibernate.hbm.xml代码如实:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!--
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
-->
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="com.mr.cheng.entity.Company" />
<mapping class="com.mr.cheng.entity.Person" />
</session-factory>
</hibernate-configuration>
3、测试类代码如下:
package com.mr.cheng.test;
import java.util.Date;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mr.cheng.entity.Company;
import com.mr.cheng.entity.Person;
public class HibernateTest {
private static SessionFactory sessionFactory;
//@BeforeClass
public static void beforeClass() {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
//@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);
}
public static void main(String[] args) {
beforeClass();
}
/**
* 单向多对一
* 两边手动保存,
*/
@Test
public void testAddPersonAndCompany(){
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Company company = new Company();
company.setName("rtl11");
Person p1 = new Person();
p1.setAge(33);
p1.setName("user1");
p1.setPrice(33.3);
p1.setCompany(company);
Person p2 = new Person();
p2.setAge(33);
p2.setName("user1");
p2.setPrice(33.3);
p2.setCompany(company);
session.save(company);
session.save(p1);
session.save(p2);
session.getTransaction().commit();
}
/**
* 单向保存
*/
@Test
public void addPerson(){
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Company company = (Company) session.load(Company.class, 1);
Person p1 = new Person();
p1.setAge(33);
p1.setName("user4");
p1.setPrice(33.3);
p1.setCompany(company);
Person p2 = new Person();
p2.setAge(33);
p2.setName("user4");
p2.setPrice(33.3);
p2.setCompany(company);
session.save(p1);
session.save(p2);
session.getTransaction().commit();
}
@Test
public void queryPerson(){
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person p = (Person) session.get(Person.class, 2);
if(p != null){
System.out.println(p.getName());
System.out.println(p.getCompany());
}
session.getTransaction().commit();
}
/**
* 多对一代码测试
*/
@Test
public void testOneToManyQueryCompany(){
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Company company = (Company) session.load(Company.class, 1);
if(company != null){
for(int i = 0 ; i < company.getPersons().size() ; i++){
}
}
session.getTransaction().commit();
}
}