1.Hibernate关联映射注解之一对一单向外键关联

关系映射级别注解:
       1.一对一单向外键
       2.一对一双向外键关联
       3.一对一单向外键联合主键
       4.多对一单向外键关联
       5.一对多单向外键关联
       6.一对多双向外键关联
       7.多对多单向外键关联
       8.多对多双向外键关联

实体之间的映射关系:
       一对一:一个公民对应一个身份证号码。
       一对多(多对一):一个公民有多个银行账号。
       多对多:一个学生有多个老师,一个老师有多个学生。



1.Hibernate关联映射注解之一对一单向外键关联

一对一单向外键

@OnetoOne(cascade=CascadeType.ALL)
@JoinColumn(name="pid", unique=true)
//注意:保存时应该先保存外键对象,再保存主表对象

1.配置文件

hibernate.cfg.xml



<hibernate-configuration>
    <session-factory>
        <property name="connection.username">rootproperty> 
        <property name="connection.password">123456property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driverproperty> 
        <property name="connection.url">jdbc:mysql:///hibernate?userUnicode=true&charaterEncoding=UTF-8property>
        <property name="dialect">org.hibernate.dialect.MySQLDialectproperty> 

        <property name="show_sql">trueproperty> 
        <property name="format_sql">trueproperty> 
        <property name="hibernate.default_schema">hibernateproperty>  
        <property name="hbm2ddl.auto">updateproperty> 

        <property name="current_session_context_class">threadproperty> 
        
        <mapping class="oto_fk.Students"/>
        <mapping class="oto_fk.IdCard"/>
    session-factory>
hibernate-configuration>

2.实体类

Students.java

package oto_fk;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity; //JPA注解
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

import org.hibernate.annotations.GenericGenerator;

//学生类
@Entity
public class Students{

    private IdCard idCard;
    private int sid; // 学号
    private String gender; // 性别
    private Date birthday; // 出生日期

    public Students() {

    };

    public Students(IdCard idCard, String gender, Date birthday) {
        this.idCard = idCard;
        this.gender = gender;
        this.birthday = birthday;
    }

    @Id
    @GeneratedValue //由于使用的是MySQL,主键默认整型自增长
    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="pid", unique=true)
    public IdCard getIdCard() {
        return idCard;
    }

    public void setIdCard(IdCard idCard) {
        this.idCard = idCard;
    }

    @Override
    public String toString() {
        return "Students [sid=" + sid + ", gender=" + gender + ", birthday=" + birthday
                + "]";
    }

}


IdCard.java:

package oto_fk;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;


//省份证类

@Entity
public class IdCard {

    @Id
    @GeneratedValue(generator="pid")
    @GenericGenerator(name="pid", strategy="assigned") //主键生成策略,手动配置
    @Column(length=18) //字段长度为18,不写则无法生成表结构
    private String pid; //身份证号
    private String sname; //姓名

    public IdCard() {

    }

    public IdCard(String pid, String sname) {
        this.pid = pid;
        this.sname = sname;
    }

    public String getPid() {
        return pid;
    }
    public void setPid(String pid) {
        this.pid = pid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }


}

3.测试文件

package oto_fk;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;


public class ObjectTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Test
    public void testSaveStudentWithImage() throws Exception{
        //创建配置对象
        Configuration config = new Configuration().configure(); //hibernate.cfg.xml
        //创建服务注册对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工产对象
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        //session = sessionFactory.openSession();
        //开启事务
        //transaction = session.beginTransaction();

        SchemaExport  export = new SchemaExport(config);
        export.create(true, true); //创建生成表结构

    }

    @Test
    public void testSaveStudent() throws Exception{
        //创建配置对象
        Configuration config = new Configuration().configure(); //hibernate.cfg.xml
        //创建服务注册对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工产对象
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        session = sessionFactory.getCurrentSession();
        //开启事务
        transaction = session.beginTransaction();
        //先生成身份证类对象
        IdCard idCard = new IdCard("123456789012345678", "lise");
        //再生成学生类对象
        Students stu = new Students(idCard, "nv", new Date());
        //先保存身份证类对象
        session.save(idCard);
        session.save(stu);

        //提交事务
        transaction.commit();

    }
}

你可能感兴趣的:(Hibernate)