本例以Windows, JDK1.8, MySQL5 为基础,演示使用Hibernate5以注解的方式完成一对一的关系映射。
使用的工具及技术
1.Hibernate 5.2.10.Final
2.MySQL 5
3.Eclipse
4.Maven 3
一对一表的映射
Model
分别创建Student和Transcripts两个Model对象,以Student的”S_ID”作为Transcripts里的外键。
Student.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| package com.devnp.hibernate.association.oto.model;
import java.io.Serializable; import java.util.Date;
import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType;
@Entity @Table(name = "Student") public class Student implements Serializable{
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "S_ID") private Long sid ; @Column(name = "NAME", nullable= false) private String name ; @Column(name = "AGE", nullable= false) private Integer age ; @Column(name = "BIRTH_DATE") @Temporal(TemporalType.DATE) private Date birthDate ; @OneToOne(fetch = FetchType.LAZY, mappedBy="student", cascade = CascadeType.ALL) private Transcripts transcripts ;
public Student() { super(); }
public Long getSid() { return sid; }
public void setSid(Long sid) { this.sid = sid; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public Date getBirthDate() { return birthDate; }
public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Transcripts getTranscripts() { return transcripts; }
public void setTranscripts(Transcripts transcripts) { this.transcripts = transcripts; }
@Override public String toString() { return "Student [sid=" + sid + ", name=" + name + ", age=" + age + ", birthDate=" + birthDate + "]"; }
}
|
Transcripts.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| package com.devnp.hibernate.association.oto.model;
import java.io.Serializable; import java.util.Date;
import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table;
import org.hibernate.annotations.CreationTimestamp;
@Entity @Table(name = "Transcripts") public class Transcripts implements Serializable{
private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "T_ID") private long transcriptsId ; @Column(name = "MATH_SCORES") private Double mathScores ; @Column(name = "ENGLISH_SCORES") private Double englishScores ; @Column(name = "CREATE_TIME") @CreationTimestamp private Date createTime; @OneToOne() @JoinColumn(name="S_ID") private Student student ; public Transcripts() { super(); }
public long getTranscriptsId() { return transcriptsId; }
public void setTranscriptsId(long transcriptsId) { this.transcriptsId = transcriptsId; }
public Double getMathScores() { return mathScores; }
public void setMathScores(Double mathScores) { this.mathScores = mathScores; }
public Double getEnglishScores() { return englishScores; }
public void setEnglishScores(Double englishScores) { this.englishScores = englishScores; }
public Date getCreateTime() { return createTime; }
public void setCreateTime(Date createTime) { this.createTime = createTime; }
public Student getStudent() { return student; }
public void setStudent(Student student) { this.student = student; }
@Override public String toString() { return "Transcripts [transcriptsId=" + transcriptsId + ", mathScores=" + mathScores + ", englishScores=" + englishScores + ", createTime=" + createTime + "]"; }
}
|
Hibernate SessionFactory
本例以属性配置的加载,更多获取SessionFactory的方式:Hibernate5 SessionFactory 的获取
HibernateProUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package com.devnp.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import com.devnp.hibernate.association.otm.model.Book; import com.devnp.hibernate.association.otm.model.Person; import com.devnp.hibernate.association.oto.model.Student; import com.devnp.hibernate.association.oto.model.Transcripts;
public class HibernateProUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() { Properties properties = new Properties(); properties.put("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect"); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.hbm2ddl.auto","update"); properties.put("hibernate.format_sql", "true"); properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); properties.put("hibernate.connection.password", "!qaz2wsx"); properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/test"); properties.put("hibernate.connection.username", "root");
StandardServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(properties).build(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(Student.class).addAnnotatedClass(Transcripts.class); metadataSources.addAnnotatedClass(Person.class).addAnnotatedClass(Book.class); Metadata metadata = metadataSources.getMetadataBuilder().applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build(); sessionFactory = metadata.getSessionFactoryBuilder().build(); return sessionFactory; }
public static SessionFactory getSessionFactory() { return sessionFactory; }
public static void shutdown() { getSessionFactory().close(); } }
|
测试
测试添加学生和成绩:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public static void save(){ SessionFactory sessionFactory = HibernateProUtil.getSessionFactory() ; Session session = sessionFactory.openSession() ; session.beginTransaction(); Student student = new Student() ; student.setName("XIAO LI"); student.setAge(22); student.setBirthDate(new Date()); Transcripts transcripts = new Transcripts(); transcripts.setMathScores(99.22D); transcripts.setEnglishScores(89.00D); student.setTranscripts(transcripts); transcripts.setStudent(student); session.save(student); session.getTransaction().commit(); HibernateProUtil.shutdown(); }
|
运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| create table Student ( S_ID bigint not null auto_increment, AGE integer not null, BIRTH_DATE date, NAME varchar(255), primary key (S_ID) ) engine=InnoDB Hibernate: create table Transcripts ( T_ID bigint not null auto_increment, CREATE_TIME datetime, ENGLISH_SCORES double precision, MATH_SCORES double precision, S_ID bigint, primary key (T_ID) ) engine=InnoDB Hibernate: alter table Transcripts add constraint FK6gcuorbeqm4vf9xryvg8v07gx foreign key (S_ID) references Student (S_ID) Hibernate: insert into Student (AGE, BIRTH_DATE, NAME) values (?, ?, ?) Hibernate: insert into Transcripts (CREATE_TIME, ENGLISH_SCORES, MATH_SCORES, S_ID) values (?, ?, ?, ?)
|
更多操作
查询信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public static void select(){ SessionFactory sessionFactory = HibernateProUtil.getSessionFactory() ; Session session = sessionFactory.openSession() ; session.beginTransaction(); Student student = (Student) session.get(Student.class, 2L); System.out.println(student); System.out.println("-------------------"); System.out.println(student.getTranscripts()); session.getTransaction().commit(); HibernateProUtil.shutdown(); }
|
更新操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public static void update(){ SessionFactory sessionFactory = HibernateProUtil.getSessionFactory() ; Session session = sessionFactory.openSession() ; session.beginTransaction(); String hql = "from Student where sid=:sid" ; Student student = (Student) session.createQuery(hql).setParameter("sid", 1L).uniqueResult(); System.out.println(student); System.out.println("-------------------"); System.out.println(student.getTranscripts()); student.setName("XIAO WANG"); student.getTranscripts().setEnglishScores(100D); session.update(student); session.getTransaction().commit(); HibernateProUtil.shutdown(); }
|
删除操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public static void delete(){ SessionFactory sessionFactory = HibernateProUtil.getSessionFactory() ; Session session = sessionFactory.openSession() ; session.beginTransaction(); String hql = "from Student where sid=:sid" ; Student student = (Student) session.createQuery(hql).setParameter("sid", 1L).uniqueResult(); session.delete(student); session.getTransaction().commit(); HibernateProUtil.shutdown(); }
|
代码下载
java-hibernate-association-demo.zip
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE