Java Persistence API (JPA),Java 持久层 API,是 JCP 组织发布的 Java EE 标准规范,通过注解或 XML 描述实体对象和数据库表的映射关系。
Hibernate 实现了 JPA 规范,以下展示 Hibernate JPA 开发的完整步骤:

(1) 使用 Maven 管理 Hibernate 依赖

参看 4 Hibernate:使用注解(Annotation)

(2) 创建 JPA 配置文件 persistence.xml

Hibernate JPA 开发不需要创建 Hibernate 特定配置文件 hibernate.cfg.xml,取而代之的是创建 JPA 自有配置文件 persistence.xml,JPA 规范定义的启动过程不同于 Hibernate 启动过程。
JPA 配置文件 persistence.xml 需要放在类路径下 META-INF 目录中,内容如下

<persistence xmlns="http://java.sun.com/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"version="2.0"><persistence-unit name="hibernate.jpa"><description>Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide</description><class>hibernate.Person</class><properties><property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /><property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" /><property name="javax.persistence.jdbc.user" value="root" /><property name="javax.persistence.jdbc.password" value="123456" /><property name="hibernate.show_sql" value="true" /><property name="hibernate.hbm2ddl.auto" value="create" /></properties></persistence-unit></persistence>

注意:
需要为 persistence-unit 设置 name 属性,此名称唯一;
对比 hibernate.cfg.xml,除数据库连接配置部分属性名称有所不同,其他配置保持一致。

(3) 使用注解创建持久化类

package hibernate;import java.util.Date;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;import org.hibernate.annotations.GenericGenerator;@Entity
@Table(name = "person")
public class Person {private int id;private String account;private String name;private Date birth;public Person() {}public Person(String account, String name, Date birth) {this.account = account;this.name = name;this.birth = birth;}@Id // 实体唯一标识@GeneratedValue(generator = "increment") // 使用名为“increment”的生成器@GenericGenerator(name = "increment", strategy = "increment") // 定义名为“increment”的生成器,使用Hibernate的"increment"生成策略,即自增public int getId() {return id;}public void setId(int id) {this.id = id;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Temporal(TemporalType.TIMESTAMP)public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}@Overridepublic String toString() {return "Person [id=" + id + ", account=" + account + ", name=" + name + ", birth=" + birth + "]";}}

(4) 通过 JPA API 编写访问数据库的代码

package hibernate;import java.text.ParseException;
import java.util.Date;
import java.util.List;import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;import org.junit.After;
import org.junit.Before;
import org.junit.Test;public class EntityManagerIllustrationTest {private EntityManagerFactory entityManagerFactory;@Beforepublic void setUp() throws Exception {entityManagerFactory = Persistence.createEntityManagerFactory("hibernate.jpa");}@Afterpublic void tearDown() throws Exception {entityManagerFactory.close();}@Testpublic void test() throws ParseException {EntityManager entityManager = entityManagerFactory.createEntityManager();entityManager.getTransaction().begin();entityManager.persist(new Person("tony", "Tony Stark", new Date()));entityManager.persist(new Person("hulk", "Bruce Banner", new Date()));entityManager.getTransaction().commit();entityManager.close();entityManager = entityManagerFactory.createEntityManager();entityManager.getTransaction().begin();List<Person> result = entityManager.createQuery("FROM Person", Person.class).getResultList();for (Person person : result) {System.out.println(person);}entityManager.getTransaction().commit();entityManager.close();}}

单元测试日志:

六月 26, 2017 12:01:22 上午 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [name: hibernate.jpa...]
六月 26, 2017 12:01:23 上午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
六月 26, 2017 12:01:23 上午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
六月 26, 2017 12:01:23 上午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
六月 26, 2017 12:01:23 上午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Mon Jun 26 00:01:29 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
六月 26, 2017 12:01:30 上午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists PERSON
六月 26, 2017 12:01:32 上午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@73511076] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table PERSON (ID integer not null auto_increment, ACCOUNT varchar(255), NAME varchar(255), BIRTH datetime, primary key (ID)) engine=MyISAM
六月 26, 2017 12:01:32 上午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@42257bdd] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
六月 26, 2017 12:01:33 上午 org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@4b629f13'
Hibernate: insert into PERSON (ACCOUNT, NAME, BIRTH) values (?, ?, ?)
Hibernate: insert into PERSON (ACCOUNT, NAME, BIRTH) values (?, ?, ?)
六月 26, 2017 12:01:33 上午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select person0_.ID as ID1_0_, person0_.ACCOUNT as ACCOUNT2_0_, person0_.NAME as NAME3_0_, person0_.BIRTH as BIRTH4_0_ from PERSON person0_
Person [id=1, account=tony, name=Tony Stark, birth=2017-06-26 00:01:33.0]
Person [id=2, account=hulk, name=Bruce Banner, birth=2017-06-26 00:01:34.0]
六月 26, 2017 12:01:34 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/test]

数据库查询结果:

5 Hibernate:Java Persistence API (JPA) 入门相关推荐

  1. Java Persistence API:快速入门

    各位读者好! 在我的一些朋友提出无数请求之后,我决定写一篇关于Java Persistence API的简短文章. 面向对象的编程范式是当​​今最流行和使用最广泛的模型,它具有无缝建模现实生活实体的能 ...

  2. 什么是JPA(Java persistence API)?

    通常所说的jpa指的是啥? 1. JPA概念 Java persistence API 的简称,中文名是Java持久层API,是JDK5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象 ...

  3. JPA(Java Persistence API )

    ORM概述 ORM(Object-Relational Mapping) 表示对象关系映射.在面向对象的软件开发中,通过ORM,就可以把对象映射到关系型数据库中.只要有一套程序能够做到建立对象与数据库 ...

  4. Java Persistence API中的FetchType LAZY和EAGER之间的区别?

    我是Java Persistence API和Hibernate的新手. Java Persistence API中的FetchType.LAZY和FetchType.EAGER什么区别? #1楼 我 ...

  5. JPA(Java Persistence API,Java持久化API)

    一.什么是JPA 对象关系映射ORM(Object-Relation Mapping)是用来将对象和对象之间的关系对应到数据库中表与表之间的关系的一种模式.ORM框架能够将Java对象映射到关系数据库 ...

  6. 【中英双语】Java Persistence Hibernate 和 JPA 基础教程

    [中英双语]Java Persistence Hibernate 和 JPA 基础教程 关于 Java Persistence API (JPA) 与 Hibernate 的简单易学和易于理解的课程 ...

  7. Spring Data 系列(二) Spring+JPA入门(集成Hibernate)

    通过[Spring Data 系列(一) 入门]的介绍,通过对比的方式认识到Spring提供的JdbcTemplate的强大功能.通过使用JdbcTemplate,操作数据库,不需要手动处理Conne ...

  8. JPA入门例子(采用JPA的hibernate实现版本)

    http://blog.csdn.net/hmk2011/article/details/6289151(1).JPA介绍: JPA全称为Java Persistence API ,Java持久化AP ...

  9. 芋道 Spring Boot JPA 入门(一)之快速入门

    点击上方"芋道源码",选择"设为星标" 做积极的人,而不是积极废人! 源码精品专栏 原创 | Java 2019 超神之路,很肝~ 中文详细注释的开源项目 RP ...

最新文章

  1. h5 移动端 常见 重要问题记录
  2. flink on yarn HA高可用集群搭建
  3. Linux里面lvs的基础命令,Linux中使用ipvsadm配置LVS集群的基本方法
  4. 孙鑫VC学习笔记:第一讲 Windows程序内部运行原理
  5. python dicom 三维重建_DICOM HTML5 Viewer中的真三维重建
  6. 抽奖随机滚动_老板让我做年会抽奖系统,我用Excel制作内定抽到自己的大奖!...
  7. 该死的clear 根本不释放内存,怎么才能释放泛型LIST的内存?
  8. Python之温度转换
  9. 洛谷-P1424-小鱼的航程
  10. 【Tensorflow+自然语言处理+LSTM】搭建智能聊天客服机器人实战(附源码、数据集和演示 超详细)
  11. 关于ROS功能包里package.xml和CMakeList.txt的源码分析
  12. 高精度脚印效果制作原理
  13. 电源适配器适用GB8898-2001和GB4943-2001的差异
  14. JAVA设计模式什么鬼(策略)——作者:凸凹里歐
  15. 老猿学5G专栏文章目录
  16. 讯搜 配置mysql_Xunsearch迅搜(基于 xapian+scws 的开源中文搜索引擎)安装与简单使用...
  17. HALCON图像的转换
  18. 减轻剪辑工作必备——Python实现让视频自动打码,再也不怕出现少儿不宜的画面了
  19. js和java script,js动态添加javascript标签
  20. 高仿新闻教程-开源框架的简单实现——网易新闻的标题栏(一)

热门文章

  1. 少吃柿子、山楂、黑枣,警惕鞣酸
  2. 【Optimizaition/x86】Intel CPU的CPUID指令获取的C实现
  3. 祝全天下老师教师节快乐
  4. 矩阵理论复习(十一)
  5. 深度:养老康复器械龙头即将上市,美的、新松进军养老康复机器人,老龄化加速千亿康复市场到来!
  6. 解决:浏览器下载的Excel文件显示“文件已损坏,无法打开”
  7. AI 操控战斗机战胜飞行员?道翰天琼认知智能机器人平台API接口大脑为您揭秘-3。
  8. Nginx负载均衡四种分配策略
  9. Failed to load response data:No data found for resource with given identifier
  10. 一些关于网页设计的优秀网站