国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專(zhuān)欄INFORMATION COLUMN

慕課網(wǎng)_《Hibernate注解》學(xué)習(xí)總結(jié)

Jaden / 654人閱讀

摘要:時(shí)間年月日星期二說(shuō)明本文部分內(nèi)容均來(lái)自慕課網(wǎng)。文件如下在目錄下,創(chuàng)建文件指定映射文件的路徑注解映射實(shí)體類(lèi)可選,對(duì)應(yīng)數(shù)據(jù)庫(kù)中的一個(gè)表。

時(shí)間:2017年07月11日星期二
說(shuō)明:本文部分內(nèi)容均來(lái)自慕課網(wǎng)。@慕課網(wǎng):http://www.imooc.com
教學(xué)源碼:無(wú)
學(xué)習(xí)源碼:https://github.com/zccodere/s...

第一章:類(lèi)級(jí)別注解 1-1 本章簡(jiǎn)介

本章簡(jiǎn)介

Hibernate注解簡(jiǎn)介
JPA與Hibernate的關(guān)系
Hibernate注解分類(lèi)
@Entity
@Table
@Embeddable
schema與catalog

Hibernate注解簡(jiǎn)介

使用注解的目的:為了簡(jiǎn)化繁瑣的ORM映射文件(*.hbm)的配置

JPA與Hibernate的關(guān)系

什么是JPA
    全稱(chēng)Java Persistence API
    JPA注解是JavaEE的規(guī)范和標(biāo)準(zhǔn)
JPA和Hibernate的關(guān)系:

JPA是標(biāo)準(zhǔn)接口
Hibernate是實(shí)現(xiàn),但是其功能是JPA的超集

Hibernate如何實(shí)現(xiàn)與JPA的關(guān)系
    通過(guò)hibernate-annotation
    hibernate-entitymanager
    hibernate-core三個(gè)組件來(lái)實(shí)現(xiàn)
一般在實(shí)際開(kāi)發(fā)中,優(yōu)先考慮使用JPA注解

這樣更有利于程序的移植和擴(kuò)展
Hibernate注解的分類(lèi)

類(lèi)級(jí)別注解
屬性級(jí)別注解
映射關(guān)系注解

類(lèi)級(jí)別注解

@Entity:表示一個(gè)實(shí)體,一個(gè)實(shí)體對(duì)應(yīng)數(shù)據(jù)庫(kù)一張表
@Table:配置表的屬性
@Embeddable:表示當(dāng)前類(lèi)是一個(gè)嵌入類(lèi)
1-2 準(zhǔn)備工作

回顧hibernate.cfg.xml

創(chuàng)建一個(gè)名為hibernateca的maven項(xiàng)目,并添加相關(guān)依賴(lài)。POM文件如下


  4.0.0

  com.myimooc
  hibernateca
  0.0.1-SNAPSHOT
  jar

  hibernateca
  http://maven.apache.org


        UTF-8
        UTF-8
    

    
        
        
            org.hibernate
            hibernate-core
            4.2.4.Final
        

        
        
            mysql
            mysql-connector-java
            5.1.38
        
        
        
            junit
            junit
            4.10
            test
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                
            
        
    

在src/main/ resources目錄下,創(chuàng)建hibernate.cfg.xml文件




    
        org.hibernate.dialect.MySQLDialect
        com.mysql.jdbc.Driver
        root
        root
        
            
        
        true
        update
         
        
         

    
1-3 @Entity注解

@Entity

@Entity:映射實(shí)體類(lèi)
@Entity(name=”tableName”)
name:可選,對(duì)應(yīng)數(shù)據(jù)庫(kù)中的一個(gè)表。若表名與實(shí)體類(lèi)名相同,則可以省略
注意:使用@Entity時(shí)必須指定實(shí)體類(lèi)的主鍵屬性

代碼演示

1.編寫(xiě)Students實(shí)體類(lèi)

package com.myimooc.hibernateca.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
//JPA注解
@Entity(name="t_students")
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    private Integer sid;
    /** 姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    
    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
        super();
    }
    public Students(Integer sid, String sname, String gender, Date birthday, String major) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        this.address = address;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

2.配置映射


 

3.編寫(xiě)StudentTest測(cè)試類(lèi)

package com.myimooc.hibernateca.entity;

import org.hibernate.SessionFactory;
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;

/**
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
public class StudentsTest {
    
    @Test
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        @SuppressWarnings("unused")
        SessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
        SchemaExport export = new SchemaExport(config);
        
        export.create(true, true);
    }
    
}
1-4 @Table注解

@Table

@Table(name=””,catalog=””,schema=””)
@Entity配置使用,只能標(biāo)注在實(shí)體的class定義處,表示實(shí)體對(duì)應(yīng)的數(shù)據(jù)庫(kù)表的信息
name:可選,映射表的名稱(chēng),默認(rèn)表名和實(shí)體名稱(chēng)一致,只有在不一致的情況下才需要指定表名
catalog:可選,表示目錄Catalog名稱(chēng),默認(rèn)為Catalog(“”)
schema:可選,表示模式Schema名稱(chēng),默認(rèn)為Schema(“”)

schema與catalog示意圖

schema與catalog

從實(shí)現(xiàn)的角度來(lái)看,各種數(shù)據(jù)庫(kù)系統(tǒng)對(duì)Catalog和Schema的支持和實(shí)現(xiàn)方式千差萬(wàn)別的

供應(yīng)商的支持和實(shí)現(xiàn)

代碼演示,修改Student類(lèi)如下

package com.myimooc.hibernateca.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
//JPA注解
//@Entity(name="t_students")

@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    private Integer sid;
    /** 姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    
    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
        super();
    }
    public Students(Integer sid, String sname, String gender, Date birthday, String major) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}
1-5 @Embeddable注解

@Embeddable
@Embeddable表示一個(gè)非Entity類(lèi)可以嵌入到另一個(gè)Entity類(lèi)中作為屬性而存在

代碼演示

1.編寫(xiě)Address類(lèi)

package com.myimooc.hibernateca.entity;

import javax.persistence.Embeddable;

/**
 * 地址類(lèi)(嵌入類(lèi))
 * @author ZhangCheng on 2017-07-12
 *
 */
// 表示是一個(gè)嵌入類(lèi),這個(gè)類(lèi)的對(duì)象在另一個(gè)實(shí)體類(lèi)中充當(dāng)屬性
@Embeddable
public class Address {
    
    /** 郵編 */
    private String postCode;
    /** 地址 */
    private String address;
    /** 聯(lián)系電話 */
    private String phone;
    
    @Override
    public String toString() {
        return "Address [postCode=" + postCode + ", address=" + address + ", phone=" + phone + "]";
    }
    
    public Address() {
    }
    
    public Address(String postCode, String address, String phone) {
        this.postCode = postCode;
        this.address = address;
        this.phone = phone;
    }
    
    public String getPostCode() {
        return postCode;
    }
    public void setPostCode(String postCode) {
        this.postCode = postCode;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    
}

2.修改Student類(lèi)如下

package com.myimooc.hibernateca.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
//JPA注解
//@Entity(name="t_students")

@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    private Integer sid;
    /** 姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    /** 地址 */
    private Address address;
    
    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
        super();
    }
    public Students(Integer sid, String sname, String gender, Date birthday, String major,Address address) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        this.address = address;
    }
    
    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}
第二章:屬性級(jí)別注解 2-1 本章簡(jiǎn)介

Hibernate屬性級(jí)別注解

添加方式:寫(xiě)在屬性字段方面 或 寫(xiě)在屬性的get訪問(wèn)器的上面
@Id
-@SequenceGenerator
@GeneratedValue
@Column
@Embedded
@EmbeddedId
-@Lob
-@Version
-@Basic
@Transient
2-2 @Id注解

@Id

@Id:必須,定義了映射到數(shù)據(jù)庫(kù)表的主鍵的屬性,
一個(gè)實(shí)體類(lèi)可以有一個(gè)或者多個(gè)屬性被映射為主鍵,
可置于主鍵屬性或者get方法前
注意:如果有多個(gè)屬性定義為主鍵屬性,
該實(shí)體類(lèi)必須實(shí)現(xiàn)serializable接口

拷貝hibernateca項(xiàng)目,重命名為hibernateaa,POM與Hibernate配置文件均相同

2-3 @GeneratedValue注解(一)

@GeneratedValue

@GeneratedValue(strategy=GenerationType,generator=””)
可選,用戶(hù)定義主鍵生成策略
strategy表示主鍵生成策略,取值有
    GenerationType.AUTO:根據(jù)底層數(shù)據(jù)庫(kù)自動(dòng)選擇(默認(rèn))
    GenerationType.INDENTITY:根據(jù)數(shù)據(jù)庫(kù)的Identity字段生成
    GenerationType.SEQUENCE:使用Sequence來(lái)決定主鍵的取值
    GenerationType.TABLE:使用指定表來(lái)決定主鍵取值,結(jié)合@TableGenerator使用

使用示例

2-4 @GeneratedValue注解(二)

代碼演示

1.修改Students類(lèi)

package com.myimooc.hibernateaa.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;

/**
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */

@SuppressWarnings("unused")
@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
    
    /** 學(xué)號(hào) */
    /* 方式一:使用自動(dòng)生成主鍵
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer sid;
    */
    
    /* 方式二:使用手工賦值方式生成主鍵
    @Id
    @GeneratedValue(generator="sid")
    @GenericGenerator(name="sid",strategy="assigned")//
    @Column(length=8)
    private String sid;
    */
    
    /* 方式三:使用復(fù)合主鍵 */
    @EmbeddedId
    private StudentsPK pk;
    
    /** 姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    /** 薪水 */
    @Transient // 表示該屬性不會(huì)被ORM映射到表里的字段
    private double salary;
    /** 地址 */
    @Embedded
    private Address address;
    
    @Override
    public String toString() {
        return "Students [pk=" + pk + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major="
                + major + ", salary=" + salary + ", address=" + address + "]";
    }
    
    public Students() {
        super();
    }
    
    public Students(StudentsPK pk, String sname, String gender, Date birthday, String major,Address address) {
        super();
        this.pk = pk;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        this.address = address;
    }
    
    public Students(StudentsPK pk, String sname, String gender, Date birthday, String major, double salary,
            Address address) {
        super();
        this.pk = pk;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        this.salary = salary;
        this.address = address;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
    public StudentsPK getPk() {
        return pk;
    }

    public void setPk(StudentsPK pk) {
        this.pk = pk;
    }

    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}
2-5 @GeneratedValue注解(三)

代碼演示

1.修改StudentsTest類(lèi)

package com.myimooc.hibernateaa.entity;

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.Before;
import org.junit.Test;

/**
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@SuppressWarnings("unused")
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
//        SchemaExport export = new SchemaExport(config);
//        export.create(true, true);
    }
    
    @Test
    public void addStudents(){
        // 創(chuàng)建會(huì)話
        Session session = sessionFactory.getCurrentSession();
        // 創(chuàng)建事務(wù)
        Transaction tx = session.beginTransaction();
        
        // 創(chuàng)建一個(gè)學(xué)生對(duì)象
        Address address = new Address("700005","湖北武當(dāng)山","18991167346");
//        Students s = new Students("S0000002","張三豐","男",new Date(),"太極拳",address);
//        
//        session.save(s);
        tx.commit();
        
    }
    
    @Test
    public void addStudentsByPk(){
        // 創(chuàng)建會(huì)話
        Session session = sessionFactory.getCurrentSession();
        // 創(chuàng)建事務(wù)
        Transaction tx = session.beginTransaction();
        
        // 創(chuàng)建一個(gè)學(xué)生對(duì)象
        Address address = new Address("700005","湖北武當(dāng)山","18991167346");
        // 創(chuàng)建學(xué)生主鍵對(duì)象
        StudentsPK pk = new StudentsPK();
        pk.setId("123456789012345678");
        pk.setSid("1235241231");
        
        Students s = new Students(pk,"張三豐","男",new Date(),"太極拳",address);
        session.save(s);
        tx.commit();
        
    }
}
2-6 @Column注解

@Column

@Column:可將屬性映射到列,使用該注解來(lái)覆蓋默認(rèn)值
@Column描述了數(shù)據(jù)庫(kù)表中該字段的詳細(xì)定義
這對(duì)于根據(jù)JPA注解生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)的工具非常有作用

常用屬性

name:可選,表示數(shù)據(jù)庫(kù)表中該字段的名稱(chēng),默認(rèn)與屬性名稱(chēng)一致
nullable:可選,表示該字段是否允許為null,默認(rèn)為true
unique:可選,表示該字段是否是唯一標(biāo)識(shí),默認(rèn)為false
length:可選,表示該字段的大小,僅對(duì)String類(lèi)型的字段有效,默認(rèn)為255
(如果是主鍵不能使用默認(rèn)值)
insertable:可選,表示在ORM框架執(zhí)行插入操作時(shí),該字段是否應(yīng)出現(xiàn)INSERT語(yǔ)句中,默認(rèn)為true
updateable:可選,表示在ORM框架執(zhí)行更新操作時(shí),該字段是否應(yīng)該出現(xiàn)在UPDATE語(yǔ)句中,默認(rèn)為true
    對(duì)于一經(jīng)創(chuàng)建就不可以更改的字段,該屬性非常有用,如對(duì)于birthday字段
2-7 @Embedded注解

@Embedded

@Embedded是注釋屬性的,表示該屬性的類(lèi)是嵌入類(lèi)
注意:同時(shí)嵌入類(lèi)也必須標(biāo)注@Embeddable注解
2-8 @EmbeddedId注解

@EmbeddedId

@EmbeddedId使用嵌入式主鍵類(lèi)實(shí)現(xiàn)復(fù)合主鍵
注意:嵌入式主鍵類(lèi)
必須實(shí)現(xiàn)Serializable接口
必須有默認(rèn)的public無(wú)參數(shù)的構(gòu)造方法
必須覆蓋equals和hashCode方法

代碼演示

1.編寫(xiě)StudentsPK類(lèi)

package com.myimooc.hibernateaa.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 * 學(xué)生主鍵類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@Embeddable
public class StudentsPK implements Serializable{
    
    private static final long serialVersionUID = 1L;
    
    /** 省份證號(hào)碼 */
    @Column(length=18)
    private String id;
    /** 學(xué)號(hào) */
    @Column(length=10)
    private String sid;
    
    public StudentsPK() {
    }

    @Override
    public String toString() {
        return "StudentsPK [id=" + id + ", sid=" + sid + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((sid == null) ? 0 : sid.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        StudentsPK other = (StudentsPK) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (sid == null) {
            if (other.sid != null)
                return false;
        } else if (!sid.equals(other.sid))
            return false;
        return true;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSid() {
        return sid;
    }

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

    
}

2.修改Students類(lèi)

package com.myimooc.hibernateaa.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;

/**
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */

@SuppressWarnings("unused")
@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
    
    /** 學(xué)號(hào) */
    /* 方式一:使用自動(dòng)生成主鍵
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer sid;
    */
    
    /* 方式二:使用手工賦值方式生成主鍵
    @Id
    @GeneratedValue(generator="sid")
    @GenericGenerator(name="sid",strategy="assigned")//
    @Column(length=8)
    private String sid;
    */
    
    /* 方式三:使用復(fù)合主鍵 */
    @EmbeddedId
    private StudentsPK pk;
    
    /** 姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    /** 薪水 */
    @Transient // 表示該屬性不會(huì)被ORM映射到表里的字段
    private double salary;
    /** 地址 */
    @Embedded
    private Address address;
    
    @Override
    public String toString() {
        return "Students [pk=" + pk + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major="
                + major + ", salary=" + salary + ", address=" + address + "]";
    }
    
    public Students() {
        super();
    }
    
    public Students(StudentsPK pk, String sname, String gender, Date birthday, String major,Address address) {
        super();
        this.pk = pk;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        this.address = address;
    }
    
    public Students(StudentsPK pk, String sname, String gender, Date birthday, String major, double salary,
            Address address) {
        super();
        this.pk = pk;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        this.salary = salary;
        this.address = address;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
    public StudentsPK getPk() {
        return pk;
    }

    public void setPk(StudentsPK pk) {
        this.pk = pk;
    }

    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

3.修改StudentsTest類(lèi)

package com.myimooc.hibernateaa.entity;

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.Before;
import org.junit.Test;

/**
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@SuppressWarnings("unused")
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
//        SchemaExport export = new SchemaExport(config);
//        export.create(true, true);
    }
    
    @Test
    public void addStudents(){
        // 創(chuàng)建會(huì)話
        Session session = sessionFactory.getCurrentSession();
        // 創(chuàng)建事務(wù)
        Transaction tx = session.beginTransaction();
        
        // 創(chuàng)建一個(gè)學(xué)生對(duì)象
        Address address = new Address("700005","湖北武當(dāng)山","18991167346");
//        Students s = new Students("S0000002","張三豐","男",new Date(),"太極拳",address);
//        
//        session.save(s);
        tx.commit();
        
    }
    
    @Test
    public void addStudentsByPk(){
        // 創(chuàng)建會(huì)話
        Session session = sessionFactory.getCurrentSession();
        // 創(chuàng)建事務(wù)
        Transaction tx = session.beginTransaction();
        
        // 創(chuàng)建一個(gè)學(xué)生對(duì)象
        Address address = new Address("700005","湖北武當(dāng)山","18991167346");
        // 創(chuàng)建學(xué)生主鍵對(duì)象
        StudentsPK pk = new StudentsPK();
        pk.setId("123456789012345678");
        pk.setSid("1235241231");
        
        Students s = new Students(pk,"張三豐","男",new Date(),"太極拳",address);
        session.save(s);
        tx.commit();
        
    }
}
2-9 @Transient注解

@Transient

可選,表示該屬性并非一個(gè)到數(shù)據(jù)庫(kù)表的字段的映射,ORM框架將忽略該屬性,如果一個(gè)屬性并非數(shù)據(jù)庫(kù)表的字段映射,就務(wù)必將其表示為@Transient,否則ORM框架默認(rèn)其注解為@Basic
第三章:關(guān)聯(lián)映射注解 3-1 本章簡(jiǎn)介

簡(jiǎn)介

一對(duì)一單向外鍵關(guān)聯(lián)
一對(duì)一雙向外鍵關(guān)聯(lián)
一對(duì)一單向外鍵聯(lián)合主鍵
多對(duì)一單向外鍵關(guān)聯(lián)
一對(duì)多單向外鍵關(guān)聯(lián)
一對(duì)多雙向外鍵關(guān)聯(lián)
多對(duì)多單向外鍵關(guān)聯(lián)
多對(duì)多雙向外鍵關(guān)聯(lián)
3-2 實(shí)體之間的關(guān)系

實(shí)體之間的映射關(guān)系

一對(duì)一:一個(gè)公民對(duì)應(yīng)一個(gè)身份證號(hào)碼
一對(duì)多(多對(duì)一):一個(gè)公民有多個(gè)銀行賬號(hào)
多對(duì)多:一個(gè)學(xué)生有多個(gè)老師,一個(gè)老師有多個(gè)學(xué)生
3-3 一對(duì)一單向外鍵關(guān)聯(lián)(一)

一對(duì)一單向外鍵

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name=”pid”,unique=true)
注意:保存時(shí)應(yīng)該先保存外鍵對(duì)象,再保存主表對(duì)象

拷貝hibernateca項(xiàng)目,重命名為hibernatera,POM與Hibernate配置文件均相同

代碼演示

1.編寫(xiě)Students類(lèi)

package com.myimooc.hibernatera.onetoonefk;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

/**
 * 一對(duì)一單向外鍵關(guān)聯(lián)
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@Entity
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    @GeneratedValue
    private Integer sid;
    
    /** 身份證類(lèi) */
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="pid",unique=true)
    private IdCard card;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    
    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
    }
    
    public Students(IdCard card, String gender, Date birthday, String major) {
        super();
        this.card = card;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }

    public Students(IdCard card,Integer sid,  String gender, Date birthday, String major) {
        this.card = card;
        this.sid = sid;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }
    
    public IdCard getCard() {
        return card;
    }

    public void setCard(IdCard card) {
        this.card = card;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer 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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

2.編寫(xiě)IdCard類(lèi)

package com.myimooc.hibernatera.onetoonefk;

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

import org.hibernate.annotations.GenericGenerator;

/**
 * 一對(duì)一單向外鍵關(guān)聯(lián)
 * 身份證實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@Entity
public class IdCard {
    
    @Id
    @GeneratedValue(generator = "pid")
    @GenericGenerator(name="pid",strategy="assigned")
    @Column(length=18)
    /** 身份證號(hào)碼 */
    private String pid;
    /** 學(xué)生的姓名 */
    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.修改Hibernate配置文件




    
        org.hibernate.dialect.MySQLDialect
        com.mysql.jdbc.Driver
        root
        root
        
            
        
        true
        update
        thread
         
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
         
        
        
    

4.編寫(xiě)StudentsTest類(lèi)

package com.myimooc.hibernatera.onetoonefk;

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.Before;
import org.junit.Test;

/**
 * 一對(duì)一雙單外鍵關(guān)聯(lián)
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@SuppressWarnings("unused")
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
//        SchemaExport export = new SchemaExport(config);
//        
//        export.create(true, true);
    }
    
    
}
3-4 一對(duì)一單向外鍵關(guān)聯(lián)(二)

代碼演示

1.修改StudentsTest類(lèi)

package com.myimooc.hibernatera.onetoonefk;

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.Before;
import org.junit.Test;

/**
 * 一對(duì)一雙單外鍵關(guān)聯(lián)
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@SuppressWarnings("unused")
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
//        SchemaExport export = new SchemaExport(config);
//        
//        export.create(true, true);
    }
    
    /**
     * 一對(duì)一單向外鍵關(guān)聯(lián)保存測(cè)試
     */
    @Test
    public void addStudents(){
        
        Session session = sessionFactory.getCurrentSession();
        
        // 生成一個(gè)身份證對(duì)象
        IdCard card = new IdCard("123456789012345678","張無(wú)忌");
        Transaction tx = session.beginTransaction();
        // 生成學(xué)生對(duì)象
        Students s = new Students(card, "男", new Date(), "太極拳");
        // 先保存身份證類(lèi)的對(duì)象
        session.save(card);
        session.save(s);
        
        tx.commit();
        
    }
    
}
3-5 一對(duì)一雙向外鍵關(guān)聯(lián)

一對(duì)一雙向外鍵

主控方的配置同一對(duì)一單向外鍵關(guān)聯(lián)相同
@OneToOne(mappedBy=”card”)//被控方
雙向關(guān)聯(lián),必須設(shè)置mappedBy屬性。因?yàn)殡p向關(guān)聯(lián)只能交給一方去控制
不可能在雙方都設(shè)置外鍵保存關(guān)聯(lián)關(guān)系,否則雙方都無(wú)法保存

代碼演示

1.編寫(xiě)Students類(lèi)

package com.myimooc.hibernatera.onetoonebfk;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

/**
 * 一對(duì)一雙向外鍵關(guān)聯(lián)
 * 學(xué)生實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@Entity
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    @GeneratedValue
    private Integer sid;
    
    /** 身份證類(lèi) */
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="pid",unique=true)
    private IdCard card;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    
    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
    }
    
    public Students(IdCard card, String gender, Date birthday, String major) {
        super();
        this.card = card;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }

    public Students(IdCard card,Integer sid,  String gender, Date birthday, String major) {
        this.card = card;
        this.sid = sid;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }
    
    public IdCard getCard() {
        return card;
    }

    public void setCard(IdCard card) {
        this.card = card;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer 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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

2.編寫(xiě)IdCard類(lèi)

package com.myimooc.hibernatera.onetoonebfk;

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

import org.hibernate.annotations.GenericGenerator;

/**
 * 一對(duì)一雙向外鍵關(guān)聯(lián)
 * 身份證實(shí)體類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
@Entity
public class IdCard {
    
    @Id
    @GeneratedValue(generator = "pid")
    @GenericGenerator(name="pid",strategy="assigned")
    @Column(length=18)
    /** 身份證號(hào)碼 */
    private String pid;
    /** 學(xué)生的姓名 */
    private String sname;
    /** 學(xué)生的引用 */
    @OneToOne(mappedBy="card")
    private Students stu;
    
    public Students getStu() {
        return stu;
    }
    public void setStu(Students stu) {
        this.stu = stu;
    }
    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.修改hibernate配置文件




    
        org.hibernate.dialect.MySQLDialect
        com.mysql.jdbc.Driver
        root
        root
        
            
        
        true
        update
        thread
         
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
         
        
        
    

4.編寫(xiě)StudentsTest類(lèi)

package com.myimooc.hibernatera.onetoonebfk;

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.Before;
import org.junit.Test;

/**
 * 一對(duì)一雙向外鍵關(guān)聯(lián)
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-12
 *
 */
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    //@Test
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
        SchemaExport export = new SchemaExport(config);
        
        export.create(true, true);
    }
    
    /**
     * 一對(duì)一雙向外鍵關(guān)聯(lián)保存測(cè)試
     */
    @Test
    public void addStudents(){
        
        Session session = sessionFactory.getCurrentSession();
        
        // 生成一個(gè)身份證對(duì)象
        IdCard card = new IdCard("123456789012345678","張無(wú)忌");
        Transaction tx = session.beginTransaction();
        // 生成學(xué)生對(duì)象
        Students s = new Students(card, "男", new Date(), "太極拳");
        // 先保存身份證類(lèi)的對(duì)象
        session.save(card);
        session.save(s);
        
        tx.commit();
        
    }
    
}
3-6 一對(duì)一單向外鍵聯(lián)合主鍵

一對(duì)一雙向外鍵聯(lián)合主鍵

創(chuàng)建主鍵類(lèi)
主鍵類(lèi)必須實(shí)現(xiàn)serializable接口,重寫(xiě)hashCode()和equals()方法
主鍵類(lèi):@Embeddable
實(shí)體類(lèi):@EmbeddedId
3-7 多對(duì)一單向外鍵關(guān)聯(lián)(一)

多對(duì)一單向外鍵

多方持有一方的引用,比如:多個(gè)學(xué)生對(duì)應(yīng)一個(gè)班級(jí)(多對(duì)一)
在多方添加以下注解
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
@JoinColumn(name=”cid”,referencedColumnName=”CID”)

代碼演示

1.編寫(xiě)Students類(lèi)

package com.myimooc.hibernatera.manytoonefk;

import java.util.Date;

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;

/**
 * 多對(duì)一單向外鍵關(guān)聯(lián)
 * 學(xué)生實(shí)體類(lèi)(多方)
 * @author ZhangCheng on 2017-07-13
 *
 */
@Entity
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    @GeneratedValue
    private Integer sid;
    /** 學(xué)生姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;
    // 多方持有一方的引用
    @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)// 配置級(jí)聯(lián)關(guān)系和抓取策略
    @JoinColumn(name="cid",referencedColumnName="CID") // 指定外鍵
    private ClassRoom classRoom;
    
    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
    }
    
    public Students(String sname, String gender, Date birthday, String major) {
        super();
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public ClassRoom getClassRoom() {
        return classRoom;
    }

    public void setClassRoom(ClassRoom classRoom) {
        this.classRoom = classRoom;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer 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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

2.編寫(xiě)ClassRoom類(lèi)

package com.myimooc.hibernatera.manytoonefk;

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

import org.hibernate.annotations.GenericGenerator;

/**
 * 多對(duì)一單向外鍵關(guān)聯(lián)
 * 班級(jí)實(shí)體類(lèi)(一方)
 * @author ZhangCheng on 2017-07-13
 *
 */
@Entity
public class ClassRoom {
    
    /** 班級(jí)編號(hào) */
    @Id
    @GeneratedValue(generator="cid")
    @GenericGenerator(name="cid",strategy="assigned")
    @Column(length=4)
    private String cid;
    /** 班級(jí)名字 */
    private String cname;
    
    public ClassRoom() {
    }

    public ClassRoom(String cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public String getCid() {
        return cid;
    }

    public void setCid(String cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "ClassRoom [cid=" + cid + ", cname=" + cname + "]";
    }
    
    
}

3.修改hibernate配置文件




    
        org.hibernate.dialect.MySQLDialect
        com.mysql.jdbc.Driver
        root
        root
        
            
        
        true
        update
        thread
         
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
         
        
        
    

4.編寫(xiě)StudentsTest類(lèi)

package com.myimooc.hibernatera.manytoonefk;

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.Before;
import org.junit.Test;

/**
 * 多對(duì)一單向外鍵關(guān)聯(lián)
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-13
 *
 */
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    //@Test
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
        SchemaExport export = new SchemaExport(config);
        
        export.create(true, true);
    }
    
    
}
3-8 多對(duì)一單向外鍵關(guān)聯(lián)(二)

代碼演示
1.修改StudentsTest類(lèi)

package com.myimooc.hibernatera.manytoonefk;

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.Before;
import org.junit.Test;

/**
 * 多對(duì)一單向外鍵關(guān)聯(lián)
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-13
 *
 */
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    //@Test
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        // 創(chuàng)建服務(wù)注冊(cè)對(duì)象
        ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
            .applySettings(config.getProperties()).buildServiceRegistry();
        // 生成sessionFactory
        sessionFactory = config.buildSessionFactory(ServiceRegistry);
        
        SchemaExport export = new SchemaExport(config);
        
        export.create(true, true);
    }
    
    @Test
    public void addStudents(){
        
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        
        // 創(chuàng)建班級(jí)對(duì)象
        ClassRoom c1 = new ClassRoom("C001","軟件工程");
        ClassRoom c2 = new ClassRoom("C002","網(wǎng)絡(luò)工程");
        // 創(chuàng)建學(xué)生對(duì)象
        Students s1 = new Students("張三","男", new Date(), "計(jì)算機(jī)");
        Students s2 = new Students("李四","男", new Date(), "計(jì)算機(jī)");
        Students s3 = new Students("王五","女", new Date(), "計(jì)算機(jī)");
        Students s4 = new Students("趙六","女", new Date(), "計(jì)算機(jī)");
        
        s1.setClassRoom(c1);
        s2.setClassRoom(c1);
        s3.setClassRoom(c2);
        s4.setClassRoom(c2);
        
        // 先保存班級(jí)
        session.save(c1);
        session.save(c2);
        session.save(s1);
        session.save(s2);
        session.save(s3);
        session.save(s4);
        
        tx.commit();
        
    }
    
}
3-9 一對(duì)多單向外鍵關(guān)聯(lián)

一對(duì)多單向外鍵

一方持有多方的集合,一個(gè)班級(jí)有多個(gè)學(xué)生(一對(duì)多)
在一方添加以下注解
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name=”cid”)

抓取策略總結(jié)

多對(duì)一時(shí)候
多方設(shè)置EAGER:表示積極加載
一方設(shè)置LAZY:表示懶加載

代碼演示

1.編寫(xiě)Students類(lèi)

package com.myimooc.hibernatera.onetomanyfk;

import java.util.Date;

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

/**
 * 一對(duì)多單向外鍵關(guān)聯(lián)
 * 學(xué)生實(shí)體類(lèi)(多方)
 * @author ZhangCheng on 2017-07-13
 *
 */
@Entity
public class Students {
    
    /** 學(xué)號(hào) */
    @Id
    @GeneratedValue
    private Integer sid;
    /** 學(xué)生姓名 */
    private String sname;
    /** 性別 */
    private String gender;
    /** 出生日期 */
    private Date birthday;
    /** 專(zhuān)業(yè) */
    private String major;

    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
                + ", major=" + major + "]";
    }
    
    public Students() {
    }
    
    public Students(String sname, String gender, Date birthday, String major) {
        super();
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer 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;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

2.編寫(xiě)ClassRoom類(lèi)

package com.myimooc.hibernatera.onetomanyfk;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
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 org.hibernate.annotations.GenericGenerator;

/**
 * 一對(duì)多單向外鍵關(guān)聯(lián)
 * 班級(jí)實(shí)體類(lèi)(一方)
 * @author ZhangCheng on 2017-07-13
 *
 */
@Entity
public class ClassRoom {
    
    /** 班級(jí)編號(hào) */
    @Id
    @GeneratedValue(generator="cid")
    @GenericGenerator(name="cid",strategy="assigned")
    @Column(length=4)
    private String cid;
    /** 班級(jí)名字 */
    private String cname;
    
    // 一方持有多方的集合
    @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
    @JoinColumn(name="cid")
    private Set stus;
    
    public ClassRoom() {
    }

    public ClassRoom(String cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public Set getStus() {
        return stus;
    }

    public void setStus(Set stus) {
        this.stus = stus;
    }

    public String getCid() {
        return cid;
    }

    public void setCid(String cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "ClassRoom [cid=" + cid + ", cname=" + cname + "]";
    }
    
    
}

3.修改hibernate配置文件

同上

4.編寫(xiě)StudentsTest類(lèi)

package com.myimooc.hibernatera.onetomanyfk;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

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.Before;
import org.junit.Test;

/**
 * 一對(duì)多單向外鍵關(guān)聯(lián)
 * 單元測(cè)試類(lèi)
 * @author ZhangCheng on 2017-07-13
 *
 */
public class StudentsTest {
    
    private SessionFactory sessionFactory = null;
    
    @Before
    //@Test
    public void schemaExportTest(){
        // 創(chuàng)建hibernate配置對(duì)象
        Configuration config = new Configuration().configure();
        /           
               
                                           
                       
                 

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/67370.html

相關(guān)文章

  • 課網(wǎng)_《2小時(shí)學(xué)會(huì)SpringBoot》學(xué)習(xí)總結(jié)

    摘要:小時(shí)學(xué)會(huì)學(xué)習(xí)總結(jié)時(shí)間年月日星期六說(shuō)明本文部分內(nèi)容均來(lái)自慕課網(wǎng)。慕課網(wǎng)教學(xué)示例源碼暫無(wú)。數(shù)據(jù)庫(kù)操作下第六章事務(wù)管理事務(wù)管理只有查詢(xún)的時(shí)候不加事務(wù),其它任何操作都要加事務(wù)。第七章課程回顧課程回顧總結(jié)介紹安裝配置的使用數(shù)據(jù)庫(kù)操作 《2小時(shí)學(xué)會(huì)SpringBoot》學(xué)習(xí)總結(jié) 時(shí)間:2017年2月18日星期六說(shuō)明:本文部分內(nèi)容均來(lái)自慕課網(wǎng)。@慕課網(wǎng):http://www.imooc.com教學(xué)示...

    aisuhua 評(píng)論0 收藏0
  • 課網(wǎng)_《Spring入門(mén)篇》學(xué)習(xí)總結(jié)

    摘要:入門(mén)篇學(xué)習(xí)總結(jié)時(shí)間年月日星期三說(shuō)明本文部分內(nèi)容均來(lái)自慕課網(wǎng)。主要的功能是日志記錄,性能統(tǒng)計(jì),安全控制,事務(wù)處理,異常處理等等。 《Spring入門(mén)篇》學(xué)習(xí)總結(jié) 時(shí)間:2017年1月18日星期三說(shuō)明:本文部分內(nèi)容均來(lái)自慕課網(wǎng)。@慕課網(wǎng):http://www.imooc.com教學(xué)示例源碼:https://github.com/zccodere/s...個(gè)人學(xué)習(xí)源碼:https://git...

    Ververica 評(píng)論0 收藏0
  • 課網(wǎng)_《新一代構(gòu)建工具gradle》學(xué)習(xí)總結(jié)

    摘要:時(shí)間年月日星期二說(shuō)明本文部分內(nèi)容均來(lái)自慕課網(wǎng)。項(xiàng)目一個(gè)項(xiàng)目代表一個(gè)正在構(gòu)建的組件比如一個(gè)文件,當(dāng)構(gòu)建啟動(dòng)后,會(huì)基于實(shí)例化一個(gè)類(lèi),并且能夠通過(guò)變量使其隱式可用。任務(wù)動(dòng)作定義了一個(gè)最小的工作單元。 時(shí)間:2017年05月16日星期二說(shuō)明:本文部分內(nèi)容均來(lái)自慕課網(wǎng)。@慕課網(wǎng):http://www.imooc.com教學(xué)示例源碼:無(wú)個(gè)人學(xué)習(xí)源碼:https://github.com/zccod...

    antyiwei 評(píng)論0 收藏0
  • 課網(wǎng)_Hibernate緩存策略》學(xué)習(xí)總結(jié)

    摘要:時(shí)間年月日星期二說(shuō)明本文部分內(nèi)容均來(lái)自慕課網(wǎng)。返回對(duì)象不同返回持久化實(shí)體類(lèi)對(duì)象返回代理對(duì)象。與緩存的關(guān)系不同只緩存,但不使用緩存查詢(xún)緩存除外會(huì)使用緩存。 時(shí)間:2017年07月11日星期二說(shuō)明:本文部分內(nèi)容均來(lái)自慕課網(wǎng)。@慕課網(wǎng):http://www.imooc.com教學(xué)源碼:無(wú)學(xué)習(xí)源碼:無(wú) 第一章:概述 1-1 概述 課程內(nèi)容 了解緩存 掌握Hibernate一級(jí)緩存的使用 掌握H...

    codergarden 評(píng)論0 收藏0
  • 課網(wǎng)_Hibernate初探之多對(duì)多映射》學(xué)習(xí)總結(jié)

    時(shí)間:2017年07月11日星期二說(shuō)明:本文部分內(nèi)容均來(lái)自慕課網(wǎng)。@慕課網(wǎng):http://www.imooc.com教學(xué)源碼:無(wú)學(xué)習(xí)源碼:https://github.com/zccodere/s... 第一章:應(yīng)用場(chǎng)景 1-1 多對(duì)多的應(yīng)用場(chǎng)景 案例分析:企業(yè)項(xiàng)目開(kāi)發(fā)過(guò)程中 一個(gè)項(xiàng)目可由多個(gè)員工參與開(kāi)發(fā) 一個(gè)員工可同時(shí)參與開(kāi)發(fā)多個(gè)項(xiàng)目 示意圖 showImg(https://segmentfau...

    caozhijian 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<