第6章 JPA-Java持久化API

合集下载

java jpa 用法

java jpa 用法

java jpa 用法Java JPA(Java Persistence API)是一种用于管理Java应用程序持久化数据的API。

它提供了一种标准化的方式来实现对象-关系映射(ORM),使开发人员可以通过简单的注解和接口来访问数据库。

在本文中,我们将探讨Java JPA的用法,包括实体类的创建、持久化操作、查询操作等方面。

首先,我们需要创建一个实体类,实体类对应数据库中的一张表。

在实体类中,我们需要使用JPA的注解来映射表的字段。

例如,@Entity注解用于标识一个类为实体类,@Id注解用于标识主键字段,@Column注解用于指定列的属性。

除此之外,还有许多其他的注解可以用来定义表的关系、约束等。

接下来,我们需要定义一个接口来管理实体类的持久化操作。

这个接口通常继承自JPA提供的CrudRepository接口,该接口包含了一些常用的CRUD操作方法,如save、findById、delete等。

我们可以直接使用这些方法来实现数据的增删改查操作,无需手动编写SQL语句。

在进行持久化操作时,我们需要使用JPA的EntityManager来管理实体对象的生命周期。

通过调用EntityManager的persist方法可以将实体对象持久化到数据库中,通过调用find方法可以根据主键查找实体对象,通过调用merge方法可以更新实体对象,通过调用remove方法可以删除实体对象。

除了基本的持久化操作外,我们还可以使用JPQL(Java Persistence Query Language)来进行更复杂的查询操作。

JPQL类似于SQL,但是查询的对象是实体对象而不是表。

我们可以在查询语句中使用实体类的属性来过滤和排序数据,也可以使用一些内置的函数来进行计算和聚合操作。

最后,我们需要配置一个实现JPA规范的持久化提供者,如Hibernate、EclipseLink等。

持久化提供者负责实现JPA规范定义的接口,将实体对象映射到数据库表中,并提供实现JPA的各种功能。

Springboot+SpringCloud实战(微课版)06-第六章

Springboot+SpringCloud实战(微课版)06-第六章
① 在pom.xml文件中导入JPA依赖,如程序清单6-20所示。
Springboot整合JPA
② 在application.yml文件中配置数据源信息和JPA信息,其中JPA配置中的hibernate配置 ddl-auto: update表示会根据@Entity实体类自动更新数据库表的结构,如程序清单6-21所 示。
① 在pom.xml文件中添加Druid依赖。 ② 在application.yml文件中通过type属性配置使用的数据源为DruidDataSource
SpringBoot整合数据源
SpringBoot整合数据源
③ 创建一个配置类DataSourceConfig并添加@Configuration注解,使用@Bean注解在Spring容 器中创建一个DataSource Bean 进行管理,如程序清单6-10所示。
SpringBoot整合数据源
2.添加配置 数据源相关配置可以在核心配置文件application.properties中配置(如程序清单6-2所示),也可以 在application.yml文件中配置(如程序清单6-3所示)。
SpringBoot整合数据源
补充说明:数据源的driverClassName 会根据mysql-connector-java依赖的版本而变化,在mysqlconnector-java 5中driverClassName 为com.mysql.jdbc.Driver,而在mysql-connectorjava 6及以上版本中driverClassName 为com.mysql.cj.jdbc.Driver,并且要求在url中需要配置 serverTimezone(时区信息),serverTimezone可配置UTC、Asia/Shanghai等。配置完以上信息 之后,我们就可以在代码中使用默认的数据源进行数据库的相关操作。

JavaPersistenceAPI

JavaPersistenceAPI

Persistent Fields and Properties
The persistent state of an entity can be accessed either through the entity’s instance variables or through JavaBeans-style properties. Entities may either use persistent fields or persistent properties.


If the mapping annotations are applied to the entity’s instance variables, the entity uses persistent fields. If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the entity uses persistent properties.
Entity Classes
The class must be annotated with the javax.persistence.Entity annotation. The class must have a public or protected, no-argument constructor. The class may have other constructors. The class must not be declared final. No methods or persistent instance variables must be declared final. If an entity instance be passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface. Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. Persistent instance variables must be declared private, protected, or package-private, and can only be accessed directly by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.

jpa 自动持久化 原理

jpa 自动持久化 原理

jpa 自动持久化原理JPA(Java Persistence API)是Java中一种持久化框架,它提供了一种简单而强大的方式来将Java对象映射到关系数据库中。

JPA 的自动持久化原理是通过将Java对象与数据库表进行映射,实现对象的自动保存、更新和删除。

JPA的自动持久化原理主要是通过注解或XML配置来实现的。

在Java类中,我们可以使用@Entity注解将该类标记为实体类,使用@Id注解将该类的某个属性标记为主键。

通过这样的标记,JPA就能够自动将该实体类与数据库表进行关联。

当我们对实体对象进行操作时,JPA会自动将操作转化为对数据库的增删改操作。

例如,当我们调用EntityManager的persist方法将一个实体对象持久化时,JPA会自动将该对象保存到数据库中。

当我们修改实体对象的属性时,JPA会自动更新数据库中对应的记录。

当我们调用EntityManager的remove方法删除一个实体对象时,JPA会自动删除数据库中对应的记录。

JPA的自动持久化还支持事务管理。

通过使用注解或XML配置,我们可以将一系列的数据库操作组织成一个事务。

在事务提交或回滚时,JPA会自动将对应的操作应用到数据库中。

JPA的自动持久化原理还包括了一些其他特性,如缓存管理、延迟加载等。

通过使用这些特性,我们可以提高系统的性能和效率。

总的来说,JPA的自动持久化原理是通过将Java对象与数据库表进行映射来实现的。

通过使用注解或XML配置,我们可以将实体类与数据库表进行关联,并实现对实体对象的自动保存、更新和删除。

同时,JPA还提供了事务管理、缓存管理等特性,以提高系统的性能和效率。

MyBatis核心技术全解与项目实战读书笔记

MyBatis核心技术全解与项目实战读书笔记

《MyBatis核心技术全解与项目实战》读书笔记1. 第一章 MyBatis简介本章主要介绍了MyBatis的基本概念、特点和优势,以及其在Java企业级应用开发中的重要作用。

MyBatis是一个优秀的持久层框架,它将SQL语句与Java对象映射(POJO)相结合,使得开发人员可以更加方便地操作数据库。

MyBatis的主要目标是简化数据库操作,提高开发效率,同时也提供了良好的数据封装和安全性。

SqlSessionFactory:用于创建SqlSession对象,SqlSession是MyBatis中执行SQL语句的核心接口。

SqlSession:用于执行SQL语句的会话对象,可以通过它来执行增删改查等操作。

Mapper:映射器接口,用于定义SQL语句和Java对象之间的映射关系。

Configuration:MyBatis的全局配置类,用于配置各种属性,如缓存策略、事务管理等。

插件:MyBatis的插件机制,允许开发者自定义拦截器、类型处理器等组件,以实现对MyBatis的功能扩展。

灵活性:MyBatis支持多种存储结构,如JDBC、ODBC、JNDI等,同时还支持自定义类型处理器和插件,使得MyBatis能够满足各种复杂的数据库操作需求。

易用性:MyBatis提供了简洁的XML映射文件来描述SQL语句和Java对象之间的映射关系,使得开发者无需编写复杂的SQL语句即可完成数据库操作。

性能优化:MyBatis通过一级缓存和二级缓存机制来提高查询性能,同时还支持动态SQL、分页查询等功能,使得MyBatis能够在高并发环境下保持良好的性能表现。

安全性:MyBatis提供了严格的权限控制机制,可以限制不同用户对数据库的操作权限,保证数据的安全性。

1.1 MyBatis概念及特点MyBatis是一个优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。

相比于传统的数据访问技术,MyBatis让开发者能够更加直接地与数据库交互,从而有效地避免了大量繁琐的SQL语句编写工作。

jpa标准

jpa标准

JPA标准详解一、简介Java持久化API(Java Persistence API,简称JPA)是一种用于执行SQL数据库操作的Java API。

它为面向对象的开发人员提供了一种将Java对象映射到关系数据库的方式,并提供了在Java应用程序和数据库之间进行数据交互的方法。

二、JPA的历史和发展JPA最初是由EJB 3.0规范中的CMP(容器管理持久性)模块发展而来的。

后来,这个规范被独立出来,形成了现在的JPA标准。

JPA的主要目标是简化Java 应用程序与数据库之间的交互,使得开发人员可以专注于业务逻辑的开发,而不需要关心底层的数据访问细节。

三、JPA的特性1. 简单易用:JPA提供了一种简单的方法来定义对象-关系映射(ORM),使得开发人员可以快速地将Java对象映射到数据库表。

2. 类型安全:JPA支持泛型和注解,可以在编译时检查类型错误,提高代码的健壮性和可维护性。

3. 透明性:JPA可以将复杂的数据访问逻辑隐藏在抽象层之下,使得开发人员可以专注于业务逻辑的开发。

4. 跨平台:JPA是基于Java的,因此它可以在任何支持Java的平台上运行。

四、JPA的核心概念1. 实体(Entity):实体是数据库中的一张表,它是JPA中的基本单位。

每个实体都有一个唯一的标识符,通常是主键。

2. 持久化单元(Persistence Unit):持久化单元是一组实体、存储库和其他持久化配置的集合。

它定义了应用程序与数据库之间的连接信息。

3. 存储库(Repository):存储库是一个接口,它定义了对实体进行CRUD操作的方法。

存储库可以是本地的,也可以是远程的。

4. 查询语言(Query Language):JPA支持多种查询语言,包括JPQL(Java Persistence Query Language)、Criteria API和原生SQL。

五、JPA的使用步骤1. 定义实体:使用@Entity注解定义实体类,并使用@Table注解指定对应的数据库表。

Java之jpa入门教程讲解

Java之jpa⼊门教程讲解JPA快速⼊门介绍⼀:什么是JPAJPA的英⽂全称是Java PersistenceAPI, ⽬的是给Java开发者提供对象关系映射⼯具⽤于在Java应⽤程序开发中来管理关系数据(RDBMS)。

JavaPersistence 包含下⾯三个部分:1. Java持久化API2. JPA查询语⾔3. 对象关系映射元数据⼆:JPA有哪些框架提供了的实现当前JPA提供⼚商有Hibernate, Apache, Eclipse Link等,Google云计算平台 AppEngine也使⽤了JPA作为持久层。

JPA作为持久层框架有如下优点:1. 简单易⽤,帮助开发者提供了⽣产率2. 便于维护,减低了维护成本3. 学习成本相对⽐较低。

但是JPA的缺点也是显⽽易见,JPA作为持久层有如下缺点:1. 将语⾔与数据库混在⼀起,导致数据改动以后,配置⽂件必须更新2. 对与多数据与⼤数据量处理很容易产⽣性能问题。

3. 过度封装,导致错误查找相对与JDBC等传统开发技术⽽⾔更加困难三:标准的JPA规范JSR粗略解读JPA的最新规范为JSR Java PersistenceAPI Version 2.0Entity Class – 实体类,必须使⽤注解@entity标明,同时必须有⼀个⽆参数的构造函数,⽽且⽆参数构造函数必须为public或者protected,如果⼀个entity class被标记为final将导致出错。

EntityManager – 实体管理者,管理Entity实例的整个⽣命周期,⽽且使⽤Query API来查询实体与他们的persist状态。

Query Language – 基于字符串的查询语句,⽤来查询实体(Entity)与他们的状态。

MetaModel API – 通过EntityManagerFactory或者EntityManager的getMetamodel()⽅法获取,查看persistence-unit的信息。

Java Persistence API

Java Persistence API从 EJB 技术可以开始应用时起,对其在实际应用中的可用性就一直存在怀疑。

在我看来,产生这种现象最重要的两个原因是复杂性和资源密集性。

结果,随后出现了比 EJB 更简单、具有更小资源空间的框架(比如 Spring 和 Hibernate),并且更快流行开来。

为了说明这一点,我们注意到 EJB 3.0 规范的方向相对以前出现了一个主要的转变。

作为 JSR 220 的一部分,该规范提供了类似 Plain Old Java Object (POJO) 支持、Dependency Injection (依赖注入)和注释等功能。

现在引入了一组全新的 API:Java Persistence API (JPA),以允许开发者管理 Java EE(甚至 SE)应用程序中的关系数据。

另外,Sun 声称 Java Persistence API 表现了一些 Hibernate、TopLink(二者都会在稍后讨论)、JDO 以及 EJB 框架中最好的想法。

当前,GlassFish 项目提供了实施 JPA 的一个参考,JPA 在 GlassFish 应用程序服务器中作为 TopLink Essential 部分。

您可以在 GlassFish 社区页找到该 JPA 参考实施。

不要混淆 TopLink Essentials 和 TopLink,前者现在是由 Oracle Corporation 拥有的关系映射工具。

稍后我将在本文中讨论 TopLink 框架。

让我们来讨论一些您应该考虑应用 JPA 作为持久化框架的应用场景。

何时考虑将JPA作为持久化框架您选择从流行的框架(比如 Hibernate、TopLink 和 EJB)中选择应用具有“好用”的功能且基于标准的框架。

您需要轻量级的持久化框架,且不需要 EJB 的容器提供的服务。

您需要可以在标准或 Enterprise Java 应用程序中使用的持久化框架。

JPA教程:使用Java持久性API(JPA)存储数据库对象的临时内存副本说明书

JAVA PERSISTENCEAPI (JPA)TutorialSimply Easy Learning2About the T utorialThis tutorial provides a basic understanding of how to store a copy of database objects into temporary memory using JAVA Persistence API (JPA).AudienceThis tutorial is designed for readers intend to do Java programing with Database connectivity, using Persistence API.PrerequisitesAwareness of Java programming with JDK 1.6 or later is a prerequisite to understand this tutorial. In addition, we assume the readers are acquainted with the concepts of JDBC in Java.Copyright & DisclaimerCopyright 2014 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at **************************.3T able of ContentsAbout the Tutorial (3)Audience (3)Prerequisites (3)Copyright & Disclaimer (3)Table of Contents (4)1.JPA – INTRODUCTION (7)Mismatch between Relational and Object Models (7)What is JPA? (7)Where to use JPA? (7)JPA History (8)JPA Providers (8)2.JPA – ARCHITECTURE (9)Class Level Architecture (9)JPA Class Relationships (10)3.JPA – ORM COMPONENTS (12)Object Relational Mapping (12)Advanced Features (12)ORM Architecture (12)Mapping.xml (14)Annotations (17)Java Bean Standard (19)Bean Conventions (19)44.JPA – INSTALLATION (21)Step 1 : Verify your Java Installation (21)Step 2 : Set your Java Environment (22)Step 3 : Installing JPA (22)Adding MySQL connector to the Project (27)5.JPA – ENTITY MANAGERS (29)Creating Entities (30)Persistence Operations (34)Create Employee (34)Update Employee (35)Deleting Employee (38)6.JPA – JPQL (40)Java Persistence Query language (40)Query Structure (40)Scalar and Aggregate Functions (41)Between, And, Like Keywords (43)Ordering (45)Named Queries (46)Eager and Lazy Fetching (50)7.JPA – ADVANCED MAPPINGS (51)Inheritance Strategies (51)Single Table strategy (51)Joined Table Strategy (58)5Table per Class Strategy (66)8.JPA – ENTITY RELATIONSHIPS (74)@ManyToOne Relation (74)@OneToMany Relation (81)@OneToOne Relation (89)@ManyToMany Relation (96)9.JPA – CRITERIA API (106)History of Criteria (106)Criteria Query Structure (106)Example of Criteria API (107)6JAVA PERSISTENCE API (JPA)7Any enterprise application performs database operations by storing and retrieving vast amounts of data. Despite all the available technologies for storage management, application developers normally struggle to perform database operations efficiently.Generally, Java developers use lots of code, or use the proprietary framework to interact with the database, whereas using JPA, the burden of interacting with the database reduces significantly. It forms a bridge between object models (Java program) and relational models (database program).Mismatch between Relational and Object ModelsRelational objects are represented in a tabular format, while object models are represented in an interconnected graph of object format. While storing and retrieving an object model from a relational database, some mismatch occurs due to the following reasons:∙ Granularity : Object model has more granularity than relational model.∙Subtypes : Subtypes (means inheritance) are not supported by all types of relational databases.∙Identity : Like object model, relational model does not expose identity while writing equality.∙Associations : Relational models cannot determine multiple relationships while looking into an object domain model.∙Data navigation : Data navigation between objects in an object network is different in both models.What is JP A?Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle Corporation.Where to use JP A?To reduce the burden of writing codes for relational object management, a programmer follows the ‘JPA Provider’ framework, which allows easy interaction with database instance. Here the required framework is taken over by JPA. 1.JAVA PERSISTENCE API (JPA)JP A HistoryEarlier versions of EJB, defined the persistence layer combined with the business logic layer using javax.ejb.EntityBean Interface.∙While introducing EJB 3.0, the persistence layer was separated and specified as JPA1.0 (Java Persistence API). The specifications of this API were released along with thespecifications of JAVA EE5 on May 11, 2006 using JSR 220.∙JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a part of Java Community Process JSR 317.∙JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR 338.JP A ProvidersJPA is an open source API, therefore various enterprise vendors such as Oracle, Redhat, Eclipse, etc. provide new products by adding the JPA persistence flavor in them. Some of these products include:∙Hibernate∙Eclipselink∙Toplink∙Spring Data JPA8JAVA PERSISTENCE API (JPA)9Java Persistence API is a source to store business entities as relational entities. It shows how to define a Plain Oriented Java Object (POJO) as an entity and how to manage entities with relations.Class Level ArchitectureThe following image shows the class level architecture of JPA. It shows the core classes and the interfaces of JPA.The following table describes each of the units shown in the above architecture.2.JAVA PERSISTENCE API (JPA)The above classes and interfaces are used for storing entities into a database as a record. They help programmers by reducing their efforts to write codes for storing data into a database so that they can concentrate on more important activities such as writing codes for mapping the classes with database tables.JP A Class RelationshipsIn the above architecture, the relations between the classes and interfaces belong to the javax.persistence package. The following diagram shows the relationship between them.10JAVA PERSISTENCE API (JPA)∙The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances.∙The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance.∙The relationship between EntityManager and Query is one-to-many. A number of queries can execute using one EntityManager instance.∙The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities.11JAVA PERSISTENCE API (JPA)12Most contemporary applications use relational database to store data. Recently, many vendors switched to object database to reduce their burden on data maintenance. It means object database or object relational technologies are taking care of storing, retrieving, updating, and maintaining data. The core part of this object relational technology is mapping orm.xml files. As xml does not require compilation, we can easily make changes to multiple data sources with less administration.Object Relational MappingObject Relational Mapping (ORM) briefly tells you about what is ORM and how it works. ORM is a programming ability to covert data from object type to relational type and vice versa. The main feature of ORM is mapping or binding an object to its data in the database. While mapping, we have to consider the data, the type of data, and its relations with self-entity or entities in any other table.Advanced Features∙Idiomatic persistence : It enables you to write persistence classes using object orientedclasses.∙ High Performance : It has many fetching techniques and helpful locking techniques.∙Reliable : It is highly stable and used by many professional programmers.ORM ArchitectureThe ORM architecture looks as follows.3.The above architecture explains how object data is stored into a relational database in three phases.Phase 1The first phase, named as the object data phase, contains POJO classes, service interfaces, and classes. It is the main business component layer, which has business logic operations and attributes.For example, let us take an employee database as a schema.∙Employee POJO class contains attributes such as ID, name, salary, and designation. It also contains methods like setter and getter of those attributes.∙Employee DAO/Service classes contain service methods such as create employee, find employee, and delete employee.13Phase 2The second phase, named as mapping or persistence phase, contains JPA provider, mapping file (ORM.xml), JPA Loader, and Object Grid.∙JPA Provider: It is the vendor product that contains the JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc.∙Mapping file: The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database.∙JPA Loader: The JPA loader works like a cache memory. It can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (attributes of POJO class).∙Object Grid: It is a temporary location that can store a copy of relational data, like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it affects the main database.Phase 3The third phase is the relational data phase. It contains the relational data that is logically connected to the business component. As discussed above, only when the business component commits the data, it is stored into the database physically. Until then, the modified data is stored in a cache memory as a grid format. The process of the obtaining the data is identical to that of storing the data.The mechanism of the programmatic interaction of the above three phases is called as object relational mapping.Mapping.xmlThe mapping.xml file instructs the JPA vendor to map the entity classes with the database tables.Let us take an example of Employee entity that contains four attributes. The POJO class of Employee entity named Employee.java is as follows:1415The above code is the Employee entity POJO class. It contain four attributes eid, ename, salary, and deg. Consider these attributes as the table fields in a table and eid as the primary key of this table. Now we have to design the hibernate mapping file for it. The mapping file named mapping.xml is as follows:16The above script is used for mapping the entity class with the database table. In this file, ∙<entity-mappings> tag defines the schema definition to allow entity tags into the xml file.∙<description> tag provides a description of the application.∙<entity> tag defines the entity class which you want to convert into a table in a database. Attribute class defines the POJO entity class name.∙<table> tag defines the table name. If you want to have identical names for both the class as well as the table, then this tag is not necessary.∙<attributes> tag defines the attributes (fields in a table).∙<id> tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or Taken from Sequence.∙<basic> tag is used for defining the remaining attributes of the table.∙<column-name> tag is used to set user-defined field names in the table.AnnotationsGenerally xml files are used to configure specific components, or mapping two different specifications of components. In our case, we have to maintain xml files separately in a17framework. That means while writing a mapping xml file, we need to compare the POJO class attributes with entity tags in the mapping.xml file.Here is the solution. In the class definition, we can write the configuration part using annotations. Annotations are used for classes, properties, and methods. Annotations start with ‘@’ symbol. Annotations are declared prior to a class, property, or method. All annotations of JPA are defined in the javax.persistence package.The list of annotations used in our examples are given below.18Java Bean StandardThe Java class encapsulates the instance values and their behaviors into a single unit called object. Java Bean is a temporary storage and reusable component or an object. It is a19serializable class which has a default constructor and getter and setter methods to initialize the instance attributes individually.Bean Conventions∙Bean contains its default constructor or a file that contains a serialized instance.Therefore, a bean can instantiate another bean.∙The properties of a bean can be segregated into Boolean properties or non-Boolean properties.∙Non-Boolean property contains getter and setter methods.∙Boolean property contains setter and is method.∙Getter method of any property should start with small lettered get(Java method convention) and continued with a field name that starts with a capital letter. For example, the field name is salary, therefore the getter method of this field is getSalary ().∙Setter method of any property should start with small lettered set(Java method convention), continued with a field name that starts with a capital letter and the argument value to set to field. For example, the field name is salary, therefore the setter method of this field is setSalary (double sal).∙For Boolean property, the is method is used to check if it is true or false. For example, for the Boolean property empty, the is method of this field is isEmpty ().20JAVA PERSISTENCE API (JPA)End of ebook previewIf you liked what you saw…Buy it from our store @ https://21。

java中jpa写法

java中jpa写法Java中JPA(Java Persistence API)是一个用于管理Java应用程序中的对象持久性的规范。

该规范定义了一系列接口和注解,为开发人员提供了一种简化数据库访问和操作的方法。

JPA的设计目标是提供一种通用、独立于数据库的持久化解决方案,使开发人员能够以面向对象的方式操作数据库。

在Java中使用JPA,需要先配置相关的依赖项。

通常情况下,我们会使用Maven或Gradle来管理项目依赖。

在项目的pom.xml(或build.gradle)文件中,添加JPA相关的依赖项,如Hibernate、EclipseLink等。

接下来,我们需要创建实体类。

实体类是JPA中的核心概念,它表示数据库中的表。

每个实体类通常都对应一个数据库表,每个类属性通常都对应表中的字段。

JPA提供了一组注解,用于在实体类中标识表名、字段名、关联关系等。

例如,我们有一个名为User的实体类,表示用户信息。

在该类上,我们可以使用Entity注解标识该类为一个实体类,使用Table注解指定该实体类对应的数据库表。

使用Column注解标识属性对应的字段。

EntityTable(name = "user")public class User {IdGeneratedValue(strategy = GenerationType.IDENTITY)private Long id;Column(name = "username")private String username;Column(name = "password")private String password;省略getter和setter方法}在实体类中,我们通常还会使用一些其他注解,如Id指定主键字段,GeneratedValue指定主键生成策略,OneToMany和ManyToOne指定关联关系等。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
在Java EE 5乀前,对象持丽化是通过EJB2.x的实体Bean实现
的。实体Bean是对数据库中实体的映射,需要保持实体Bean 和数据库中的信息同步。同时,实体Bean还需要封装一些对数
据库访问的常用方法。这些访问数据库的代码可以由Bean提供
者编写,也可以由容器来提供。





4
Java EE 5规范将对象持丽化从EJB中分离出来形成单独的API
在左窗格中右击,选择New…菜单项,将弹出如图6.1所示的
Database Driver对话框。





14
图6.1 创建数据库连接对话框





15
在上述对话框设置好相关的连接参数。连接MySQL数据库的相关参
数设置如下:

Driver template : 选 择 合 适 的 驱 劢 程 序 模 板 , 这 里 选 MySQL Connector/J。
在bookstore上右击并选择New Table将打开Table Wizard对
话框,在这里也可以简单地完成表的设计工作。当然,对与业人 员来说,通过SQL编辑器窗格直接输入创建表的SQL诧句更为快 捷一些。





18
(2)创建应用
由亍JPA从JDK5开始就从EJB中独立出来了,它不普通Java API





22
在这个配置文件中的相关标签是由选定的JPA实现库决定的,丌同的
另一种更好的做法是在Web服务器容器中配置数据源,Web服
务器能提供对数据源及连接池的高效管理,应用程序则通过JNDI 名访问数据源和建立至数据库的连接。





7
(2) 加载对象数据
数据加载指的是把数据库中的信息加载给应用程序的对象属性。
加载数据前必须明确对象/关系映射,包括需要明确数据来自哪个 表戒哪几个表,以及把数据加载刡哪个对象戒者哪几个对象。通 常还涉及刡数据的查询和对象信息的更新。主要工作包括:





11
(6) 其它
数据库操作常常会涉及多个对象戒多个数据库记彔,O/R映射必
须提供同时初除多个对象戒同时更新多个对象的机刢。
事务问题也是持丽化必须考虑的重要内容,ORM框架必须保证事
务的ACID特性。此外,安全性问题也是持丽化技术必须重视的课 题,丌安全的操作可能会带来灾难性的后果。




Password:输入用户登彔密码,即安装MySQL时设置的密码。
Driver JARs:点<Add JARs>添加JDBC数据库驱劢程序JAR包,如 mysql-connector-java -5.1.6-bin.jar。 Driver classname:选择戒输入JDBC驱劢程序的类名(含括包名),本例 输入com.mysql. jdbc.Driver戒org.gjt.mm.mysql.Driver。

明确数据来源表的名字; 查询涉及的字段名; 查询记彔满足的条件; 将查询结果赋给对象的属性。





8
(3) 更新实体数据
这里的实体是指数据库记彔,即把处理后的对象信息更新刡数据
库中。主要工作包括:

明确所要更新的数据库表的名字; 使用合适的方法来完成更新; 选择合适的时机执行更新。





20
图6.2 Add JPA Capabilities对话框





21
完成这一步后将会在应用的源文件夹src中创建META-INF文件夹,并
在其中创建JPA配置文件persistence.xml。以下是该文件的部分内容:
…… <persistence-unit name="bookstorePU" transaction-type= "RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider> <properties> <property name = "toplink.jdbc.driver" value = "com.mysql.jdbc. Driver"/> <property name = "toplink.jdbc.url" value = "jdbc:mysql:// 127.0.0.1: 3306/bookstore"/> <property name = "er" value = "root"/> <property name = "toplink.jdbc.password" value = "sql"/> </properties> </persistence-unit> ……
桌面工具完成。当然,MyEclipse IDE集成的数据库管理透视图 也可以完成数据库表的创建和管理。
点 击 菜 单 Windows | Open Perspective | MyEclipse
Databse Explorer,切换至MyEclipse的数据库透视图。首次 迚入该视图时,左窗格中叧有一个MyEclipse Derby的数据库连 接,双击它可以连接刡MyEclipse内置的数据库。
连接名就可看刡其中的数据库,继续展开则可查看和管理数据库 中的表、视图等各个对象。
如果bookstore尚未创建则可右击Connected to bookstore,
然后选择New SQL Editor打开SQL编辑器窗格,输入create database bookstore; 后点击执行,名为bookstore的数据库 即可创建成功。

数据库位置:指定数据库服务器地址及DBMS端口; 数据库名字:指定待访问的数据库名称; 用户名及口令:指定连接数据库的用户名及口令; 数据库驱劢程序:指定用亍连接数据库的JDBC驱劢程序。





6
为了使系统具有可移植性,通常丌宜把这些信息写在程序里。因
为数据库的配置信息可能会収生发化,如果写在程序中将给以后 的维护带来丌便。通常的做法是把这些信息写在配置文件中,配 置文件是纯文本文件,可以方便地对其迚行修改。
点 击 菜 单 MyEclipse | Project Capabilities | Add JPA
Capabilities…,弹出如图6.2所示的Add JPA Capabilities对话 框。
MyEclipse内置了多种持丽化驱劢库,如Toplink、Hibernate、
OpenJPA以及EclipseLink等,选择其中的仸一即可。本例选择 Toplink,然后点击<Next>迚入下一页,然后在Persistence unit name框中输入持丽化单元名(如bookstorePU),Driver组 合框选择在数据库管理透视图中创建的数据库连接(这里为 MySQL,如果尚未创建连接则可点Create new Driver链接立 即创建一个),Catalog/Schema组合框选择数据库名(这里为 bookstore)。最后点击<Finish>完成设置。





17
继续输入如下创建book表的SQL诧句并执行:
create table book ( bid varchar(13) primary key, bname varchar(30) not null, price float, author varchar(20), press varchar(30) );
Driver name:输入连接名,如bookstore。 Connction URL : 连 接 刡 MySQL 的 bookstore 数 据 库 的 URL 为 jdbc:mysql://127.0.0.1:3306/ bookstore。若bookstore数据库尚 未 创 建 的 话 可 先 输 入 mysql , 即 连 接 刡 MySQL 的 默 讣 数 据 库 。 127.0.0.1为数据库服务器的IP地址,这里为本机。 User name:输入数据库用户名,默讣为root。
大量数据信息的存储则普遍采用数据库方式。数据库是一种高
度结构化的文件,并可借劣数据库管理软件提供统一、高效的
数据存储、查询和管理接口。通常所说的持丽化主要指后者。





2
早期的Java程序使用JDBC来完成持丽化,这种方法虽然简单,
访问速度快,但其处理方式不面向对象模型相差甚进,导致需 要编写徆多重复的代码。丌管迚行什举样的数据库操作都需要 先建立连接对象,再建立诧句对象,在执行完操作乀后还需要 逐一关闭这些对象。





10
(5) 管理关系表
一个应用程序通常涉及一个戒多个数据库,数据库中又可能会存
在徆多表,表乀间可能会存在各种关系,就是通常所说的实体关 系。
应用程序中则通常会存在徆多对象,这些对象乀间也可能存在各
种关系,表现为对象乀间的关系。对象关系映射就是要在实体关 系不对象乀间建立起有效的同步联系。ORM框架的基本功能乀一 就是配置和维护这种联系。
可使用POJO(Plain Old Java Objects)简单对象,提高程序的
可扩展性和可移殖性;
JPA还可用亍桌面应用程序的持丽化开収。
相关文档
最新文档