本例以Windows, JDK1.8, MySQL5 为基础,演示使用Hibernate5以注解的方式完成一对多的关系映射。
使用的工具及技术
1.Hibernate 5.2.10.Final
2.MySQL 5
3.Eclipse
4.Maven 3
一对多表的映射
Model
分别创建Person和Book两个Model对象,以Student的”P_ID”作为Book里的外键, 一个人对应多个Book。
Person.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
| package com.devnp.hibernate.association.otm.model;
import java.util.HashSet; import java.util.Set;
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.OneToMany; import javax.persistence.Table;
@Entity @Table(name = "Person") public class Person {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "P_ID") private Long pId ; @Column(name = "NAME") private String name ; @Column(name = "AGE", nullable= false) private Integer age ; @OneToMany(fetch = FetchType.LAZY, mappedBy = "person", cascade=CascadeType.ALL) private Set<Book> books = new HashSet<Book>(); public Person() { super(); } public Person(String name, Integer age) { super(); this.name = name; this.age = age; }
public Long getpId() { return pId; }
public void setpId(Long pId) { this.pId = pId; }
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 Set<Book> getBooks() { return books; }
public void setBooks(Set<Book> books) { this.books = books; }
@Override public String toString() { return "Person [pId=" + pId + ", name=" + name + ", age=" + age +"]"; } }
|
Book.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
| package com.devnp.hibernate.association.otm.model;
import javax.persistence.Basic; 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.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table;
@Entity @Table(name = "Book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "B_ID") private Long bId ; @Column(name = "B_NAME") private String bName ; @Column(name = "B_PRICE") private Double price ; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "P_ID", nullable = false) private Person person ; public Book() { super(); } public Book(String bName, Double price, Person person) { super(); this.bName = bName; this.price = price; this.person = person ; }
public Long getbId() { return bId; }
public void setbId(Long bId) { this.bId = bId; }
public String getbName() { return bName; }
public void setbName(String bName) { this.bName = bName; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
public Person getPerson() { return person; }
public void setPerson(Person person) { this.person = person; }
@Override public String toString() { return "Book [bId=" + bId + ", bName=" + bName + ", price=" + price + "]"; } }
|
Hibernate SessionFactory
本例以属性配置的加载,更多获取SessionFactory的方式:Hibernate5 SessionFactory 的获取
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
|
public static void save() { SessionFactory sessionFactory = HibernateProUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.getTransaction().begin();
Person person = new Person("XIAO LI", 22);
Book book1 = new Book("A brief history of mankind", 65.11D, person); Book book2 = new Book("Math", 25.11D, person);
person.getBooks().add(book1); person.getBooks().add(book2);
session.save(person);
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 38 39 40 41 42 43 44
| create table Book ( B_ID bigint not null auto_increment, B_NAME varchar(255), B_PRICE double precision, P_ID bigint not null, primary key (B_ID) ) engine=InnoDB
create table Person ( P_ID bigint not null auto_increment, AGE integer not null, NAME varchar(255), primary key (P_ID) ) engine=InnoDB
alter table Book add constraint FKparw0y9103ja7oh11seeuw2wp foreign key (P_ID) references Person (P_ID)
insert into Person (AGE, NAME) values (?, ?)
insert into Book (B_NAME, P_ID, B_PRICE) values (?, ?, ?)
insert into Book (B_NAME, P_ID, B_PRICE) 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.getTransaction().begin();
Person person = session.get(Person.class, 1L);
System.out.println(person);
System.out.println("------------------");
System.out.println(person.getBooks());
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
|
public static void update() { SessionFactory sessionFactory = HibernateProUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.getTransaction().begin();
Person person = session.get(Person.class, 1L);
Book book = new Book("English", 35.11D, person);
person.getBooks().add(book);
session.update(person);
session.getTransaction().commit();
HibernateProUtil.shutdown(); }
|
删除对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public static void delete() { SessionFactory sessionFactory = HibernateProUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.getTransaction().begin();
Person person = session.get(Person.class, 1L);
session.delete(person);
session.getTransaction().commit();
HibernateProUtil.shutdown(); }
|
代码下载
java-hibernate-association-demo.zip
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE