JPA(Java Persistence API)通过注解或XML描述对象与关系表的映射关系,并将运行期的实体对象持久化到数据库中。
JPA是一个规范,是一个标准,Hibernate是实现了这个标准的开源框架。
1、引入hibernate-jpa-2.0-api-1.0.0.Final.jar JPA规范对应的hibernate的jar包
2、修改配置文件hibernate.cfg.xml 的映射关系<Mapping class="">
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- thread:一个线程中使用一个。获取session会话时使用--> <property name="current_session_context_class">thread</property> <!-- 是否显示SQL语句,值为布尔型,默认false --> <property name="hibernate.show_sql">true</property> <!-- 是否格式化显示sql语句,让显示更美观,值为布尔型,默认false --> <property name="hibernate.format_sql">false </property> <!-- 自动建表 update:每次执行时,无表则建表,无列则建列,只增不减 create:每次启动的时候,删除原表,再次创建 create-drop:每次启动时创建新表,当显式关闭sessionFactory时,删除表 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 连接数据库 --> <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/zxd_db</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">zxd</property> <property name="hibernate.connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 读取注解 --> <mapping class="demo.entity.Book" /> </session-factory> </hibernate-configuration>
3、实体配置
package demo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * 注解实体配置 * JPA通过注解或XML描述对象与关系表的映射关系,并将运行期的实体对象持久化到数据库中。 * @author Don * @date:日期:2017年4月19日 时间:上午10:43:00* * @version 1.0 */ //标注实体 @Entity //实体对应的表名,自动建库(若不写name,则表名与实体名保持一致) @Table(name="tb_book") public class Book { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) //主键ID注解 private int id; @Id @GenericGenerator(name="pk_uuid",strategy="uuid") @GeneratedValue(generator="pk_uuid") //生成UUID的主键注解 private String uuid; @Column //列注解 private String name; @Column private double price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
4、数据库实务session创建
package demo.util; import java.text.Annotation; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session; public class HibernateUtil { public static Session getCurrentSession() { /*注解调用使用AnnotationConfiguration 对象创建*/ // 加载Hibernate配置信息,默认读取src下的hibernate.cfg.xml Configuration cfg = new AnnotationConfiguration().configure(); // 也可以指定hibernate.cfg.xml 的路径加载 // Configuration cfg1 = new Configuration().configure(Path); /* * 应用程序从SessionFactory(会话工厂)里获得Session(会话)实例。它在多个应用线程间进行共享。 * 通常情况下,整个应用只有唯一的一个会话工厂,SessionFactory由Configuration对象创建, * 每个Hibernate配置文件,实际上是对SessionFactory的配置 */ // 试用配置信息构建sessionFactory SessionFactory factory = cfg.buildSessionFactory(); Session session =factory.getCurrentSession(); return session; } }
5、测试建表和增删改查和XML配置映射一致
(一)、 一对一映射(主键关联)
Card实体类
package demo.entity; 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.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @Table(name="ann_o2o_1_Card") public class Card { @Id @GenericGenerator(name="CreateId",strategy="foreign",parameters={ @Parameter(name="property",value="person") }) @GeneratedValue(generator="CreateId") //身份证的主键依赖于Person private int id; @Column private String code; @OneToOne(mappedBy="card") @Cascade(CascadeType.ALL) private Person person; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String card) { this.code = card; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
Person实体类
package demo.entity; 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.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name="ann_o2o_1_Person") public class Person { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String name; @OneToOne @PrimaryKeyJoinColumn @Cascade(CascadeType.ALL) //通过主键查询身份证 private Card card; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } }
(二)、一对一映射(唯一外键)
Card实体类
package demo.entity; 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.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name="ann_o2o_Card") public class Card { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String code; @OneToOne @Cascade(CascadeType.ALL) @JoinColumn(name="pid",unique=true) //生成外键列 private Person person; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String card) { this.code = card; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
Person实体类
package demo.entity; 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.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name="ann_o2o_Person") public class Person { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String name; @OneToOne(mappedBy="person") @Cascade(CascadeType.ALL) private Card card; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } }
(三)、一对多映射
Classes实体类(课程)
package demo.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name="ann_m2o_Classes") public class Classes { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String name; @OneToMany(mappedBy="cal") @Cascade(CascadeType.ALL) //一对多关系配置(配置Student实体中的Class实体映射对象,设计级联关系) private List<Student> list = new ArrayList<Student>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Student> getList() { return list; } public void setList(List<Student> list) { this.list = list; } }
Student实体类(学生)
package demo.entity; 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.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name="ann_m2o_Student") public class Student { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String name; @ManyToOne @JoinColumn(name="cid") @Cascade(CascadeType.SAVE_UPDATE) private Classes cal; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Classes getCal() { return cal; } public void setCal(Classes cal) { this.cal = cal; } }
(四)、多对多映射(中间表)
Course实体类(选课)
package demo.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; /** * 课程实体 * @author Don * @date:日期:2017年4月11日 时间:下午2:25:45* * @version 1.0 */ @Entity @Table(name="ann_m2m_Course") public class Course { @Id @GenericGenerator(name="pk_key",strategy="uuid") @GeneratedValue(generator="pk_key") private String id; @Column private String name; @ManyToMany //级联关系 @Cascade(CascadeType.SAVE_UPDATE) //中间表 @JoinTable(name="ann_m2m_stu_course", //链接当前对象的Id joinColumns={@JoinColumn(name="cid",referencedColumnName="id")}, //链接对方的表的Id inverseJoinColumns={@JoinColumn(name="stuId",referencedColumnName="id")}) private Set<Student> stus = new HashSet<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Student> getStus() { return stus; } public void setStus(Set<Student> stus) { this.stus = stus; } public Course(){} public Course(String name) { this.setName(name); } }
Student实体类(选课人员)
package demo.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; /** * 学生实体 * @author Don * @date:日期:2017年4月11日 时间:下午2:25:15* * @version 1.0 */ @Entity @Table(name="ann_m2m_Student") public class Student { @Id //生成UUID @GenericGenerator(name="pk_key",strategy="uuid") @GeneratedValue(generator="pk_key") private String id; @Column private String name; @ManyToMany //级联关系 @Cascade(CascadeType.SAVE_UPDATE) //中间表 @JoinTable(name="ann_m2m_stu_course", //链接当前对象的Id joinColumns={@JoinColumn(name="stuId",referencedColumnName="id")}, //链接对方的表的Id inverseJoinColumns={@JoinColumn(name="cid",referencedColumnName="id")}) private Set<Course> cous=new HashSet<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Course> getCous() { return cous; } public void setCous(Set<Course> cous) { this.cous = cous; } public Student() { } public Student(String name) { this.setName(name); } }
要么忍,要么狠,要么滚!