Hibernate实战——基于复合主键的关联关系

一 配置文件






     
           
           com.mysql.jdbc.Driver
           
           jdbc:mysql://localhost/hibernate
           
           root
           
           32147
           
           20
           
           1
           
           5000
           
           100
           3000
           2
           true
           
           org.hibernate.dialect.MySQL5InnoDBDialect
           
           update
           
           true
           
           true
           
           
           
     

二 PO

Person

package org.crazyit.app.domain;

import java.util.*;

import javax.persistence.*;

@Entity
@Table(name="person_inf")
public class Person
    implements java.io.Serializable
{
    // 定义first成员变量,作为标识属性的成员
    @Id
    private String first;
    // 定义last成员变量,作为标识属性的成员
    @Id
    private String last;
    private int age;
    // 记录该Person实体关联的所有Address实体
    @OneToMany(targetEntity=Address.class, mappedBy="person"
        , cascade=CascadeType.ALL)
    private Set
addresses = new HashSet<>(); // first的setter和getter方法 public void setFirst(String first) { this.first = first; } public String getFirst() { return this.first; } // last的setter和getter方法 public void setLast(String last) { this.last = last; } public String getLast() { return this.last; } // age的setter和getter方法 public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } // addresses的setter和getter方法 public void setAddresses(Set
addresses) { this.addresses = addresses; } public Set
getAddresses() { return this.addresses; } // 重写equals()方法,根据first、last进行判断 public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && obj.getClass() == Person.class) { Person target = (Person)obj; return target.getFirst().equals(this.first) && target.getLast().equals(this.last); } return false; } // 重写hashCode()方法,根据first、last计算hashCode值 public int hashCode() { return getFirst().hashCode() * 31 + getLast().hashCode(); } }

Address

package org.crazyit.app.domain;
import javax.persistence.*;

@Entity
@Table(name="address_inf")
public class Address
{
     // 标识属性
     @Id @Column(name="address_id")
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int addressId;
     // 定义代表地址详细信息的成员变量
     private String addressDetail;
     // 记录该Address实体关联的Person实体
     @ManyToOne(targetEntity=Person.class)
     // 使用@JoinColumns包含多个@JoinColumn定义外键列
     @JoinColumns({
           // 由于主表使用了复合主键(有多个主键列)
           // 因此需要使用多个@JoinColumn定义外键列来参照person_inf表的多个主键列
           @JoinColumn(name="person_first"
                , referencedColumnName="first" ,  nullable=false),
           @JoinColumn(name="person_last"
                , referencedColumnName="last" , nullable=false)
     })
     private Person person;
     // 无参数的构造器
     public Address()
     {
     }
     // 初始化全部成员变量的构造器
     public Address(String addressDetail)
     {
           this.addressDetail = addressDetail;
     }
     // addressId的setter和getter方法
     public void setAddressId(int addressId)
     {
           this.addressId = addressId;
     }
     public int getAddressId()
     {
           return this.addressId;
     }
     // addressDetail的setter和getter方法
     public void setAddressDetail(String addressDetail)
     {
           this.addressDetail = addressDetail;
     }
     public String getAddressDetail()
     {
           return this.addressDetail;
     }
     // person的setter和getter方法
     public void setPerson(Person person)
     {
           this.person = person;
     }
     public Person getPerson()
     {
           return this.person;
     }
}

三 测试

1 工具类

package lee;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil
{
    public static final SessionFactory sessionFactory;

    static
    {
        try
        {
            // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
            Configuration cfg = new Configuration()
                .configure();
            // 以Configuration实例来创建SessionFactory实例
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex)
        {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
    public static final ThreadLocal session
        = new ThreadLocal();

    public static Session currentSession()
        throws HibernateException
    {
        Session s = session.get();
        // 如果该线程还没有Session,则创建一个新的Session
        if (s == null)
        {
            s = sessionFactory.openSession();
            // 将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }

    public static void closeSession()
        throws HibernateException
    {
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

2 测试类

package lee;

import org.hibernate.Transaction;
import org.hibernate.Session;

import java.util.*;
import org.crazyit.app.domain.*;

public class PersonManager
{
    public static void main(String[] args)
    {
        PersonManager mgr = new PersonManager();
        mgr.createAndStorePerson();
        HibernateUtil.sessionFactory.close();
    }
    private void createAndStorePerson()
    {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        // 创建Person对象
        Person person = new Person();
        person.setAge(29);
        // 为复合主键的两个成员设置值
        person.setFirst("crazyit.org");
        person.setLast("疯狂Java联盟");
        Address a1 = new Address("广州天河");
        a1.setPerson(person);
        Address a2 = new Address("上海虹口");
        a2.setPerson(person);
        // 先保存主表实体
        session.save(person);
        // 再保存从表实体
        session.save(a1);
        session.save(a2);
        tx.commit();
        HibernateUtil.closeSession();
    }
}

四 测试

Hibernate:
    insert
    into
        person_inf
        (age, last, first)
    values
        (?, ?, ?)
Hibernate:
    insert
    into
        address_inf
        (addressDetail, person_last, person_first)
    values
        (?, ?, ?)
Hibernate:
    insert
    into
        address_inf
        (addressDetail, person_last, person_first)
    values
        (?, ?, ?)

Hibernate实战——基于复合主键的关联关系_第1张图片

Hibernate实战——基于复合主键的关联关系_第2张图片

你可能感兴趣的:(Hibernate,Hibernate)