官术网_书友最值得收藏!

Java Persistence API (JPA)

Before we start wielding JPA and CDI together, let’s get the basics out of the way for JPA. The Java Persistence API allows for the modelling of the domain objects for accessing, persisting, and managing data between POJOs and a relational database. JPA is the standard for working with object-relational mapping (ORM) solutions. Popular ORM solutions include Hibernate, EclipseLink (the reference implementation for all JPA versions), Apache OpenJPA, and DataNucleus. JPA puts the focus back on the domain model for retrieving and persisting data without having to deal with resource management and vendor specific SQL.

Most developers would be accustomed to hearing about Hibernate in articles and projects; it also shows up as a skill sought by employers. While Hibernate and the like can be used directly, using JPA helps us avoid falling in the vendor lock-in pit and in turn maintains portability. Hibernate is bundled as the default ORM for RedHat/JBoss servers, while EclipseLink (RI) is bundled as part of Glassfish and Payara. Similarly, Apache OpenJPA is used in TomEE.

JPA has been tagged as a maintenance release, which has led to minor but noteworthy updates in JPA 2.2. This release brings with it support for Java 8 and better CDI integration.

It all starts with an EntityManager. To work with JPA, you must obtain an EntityManager instance, which acts as the gateway to perform any database operation. The steps are outlined here:

  1. Create persistence.xml and define one or more persistence-unit in it:
      <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name="taskDb" transaction-type="JTA">
<jta-data-source>jdbc/AppDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>

</persistence>
  1. Obtain an EntityManager in a non-managed environment (using CDI):
       @Produces public EntityManager create() {
return Persistence.createEntityManagerFactory("taskDb")
.createEntityManager();
}

public void close(@Disposes EntityManager em) {
em.close();
}
  1. Obtaining an EntityManager in a managed environment can be done like so:
        @PersistenceContext(unitName="taskDb") EntityManager em;
  1. Use the EntityManager instance within a transaction to perform the operations on an entity.
主站蜘蛛池模板: 连平县| 山东| 彭山县| 上思县| 麻栗坡县| 武隆县| 徐州市| 安国市| 德阳市| 大冶市| 绥芬河市| 清涧县| 铅山县| 贡觉县| 通榆县| 桂东县| 太和县| 伊通| 温泉县| 原阳县| 卓尼县| 兴和县| 聊城市| 永丰县| 简阳市| 滨海县| 如皋市| 曲阜市| 沿河| 枣强县| 沛县| 普兰店市| 尤溪县| 云阳县| 新建县| 平陆县| 偏关县| 定西市| 蓬溪县| 青浦区| 舒城县|