JPA
Prepared by: John Tan March,
Contents
what is JPA
1.1 Introduction
1.2 architectrue
1.3 jpa-EntityManagers and Relationship
1.4 jpa-ORM Componments
1.5 jpa-annotations
1.6 a simple example
Where to use JPA
2.1 adventage
2.2 Relationship of JPA and Hibernate
2.3 example of JPA+Hibernate+spring Difference between JPA and Mybatis 1THE DESCRIPTION OF JPA
.1Introduction
JPA (Java Persistence API) is a collection of classes and methods to persistently store the vast amounts of data into database.It is use XML5 or annotations to description the mapping relationship object-relation table.You can use the JPA in Web applications and even desktop.The purpose of JPA is provide the Standard Specification for the persistence of POJO.Generally the JPA forms a bridge between object model(Java program) and relational models(database program)
1.2 architecture
EntityManageFactory:This is factory of EntityManager.It creates and manager multiple EntityManager instance.
EntityManager:It is an Interface, it manages the persistence operations on objects. It works like factory for Query instance. Entity:Entities are the persistence objects, stores as records in the database. Query:This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria. EntityTransaction:It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class. Persistence:This class contain static methods obtain EntityManagerFactory instance. 1.3 Jpa class relationship 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. Many 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.
1.4 Orm components
ORM (Object Relational Mapping) is a programming ability to covert data from object type to relational type and vice versa.
ORM Advantage:
Idiomatic persistence : It enables you to write the persistence classes using object oriented classes.
High Performance : It has many fetching techniques and hopeful locking techniques.
Reliable : It is highly stable and eminent. Used by many industrial programmers. 1.5 Jpa annotations
1.5.1Some annotations
@Entity declares the class as an entity.It is must to declares @Table declares table name,if you not declares table name then you must declares the primary key policy for “create-tables” in persistence.xml configuration file @Id Specifies the property, use for identity (primary key of a table) of the class. @OneToOne,@ManyToMany,@OneToMany,@ManyToOne, if you want to implements cascading delete
You must set “cascade = CascadeType.REMOVE” and the CascadeType has five attribute: CascadeType.ALL : It is contain all methods
CascadeType.REMOVE: if we set this in A entity,and we delete on records in A table that will delete B table which have relation record,but we can’t delete B records,It will be throws a Exception
CascadeType.PERSIST : cascade save,we can add records in A Object then B Object will increase with A add records CascadeType.MERGE:With the A Object had change then B Object has change CascadeType.REFRESH : cascade refresh @ManyToMany,@OneToMany :if we use those annotations that we must be target a entity,like
@OneToMany( targetEntity=Employee.class )
@OneToMany( targetEntity=Employee.class ) 1.5.2Automatic generation of JPA entity identify
The uniqueness of data is the basic requirement of all application,if developer or user to contain the data uniqueness that the data is not safe.So automatic generation is the method which often to use.OpenJPA support four kinds to automatic generation entity identify. Container automatic generation entity identify
Use the database automatic increment to automatic generation entity identify
According the database sequence technology
Use the database table field to generation entity identify We can use these annotations @GenerateValue,@SequenceGenerator and @TableGenerator all the these annotations are under the package javax.persistence.*
The @GenerateValue automatic generation entity identify be numeric type file,for example int ,long,short,byte etc. or their corresponding wrapper , such as Short,Long,Byte,Integer. @GenerateValue automatic generation entity identify can be String type also. the @GenerateValue have two attributes are strategy and generator. Strategy is the enumeration of GenerationType GenerationType.AUTO is OpenJPA container automatic generation entity identify,this is default
GenertaionType.INENTITY is using database auto increment field as the new increase entity unique value
GenerationType.SEQUENCE which is define using the sequence number of database as assign unique value to newly entity object as an entity sign
GenerationType.TABLE is using database one filed to record entity object sign,by this filed increase for newly entity object to assign unique value Annotation Description
@Entity Declares the class as an entity or a table.
@Table Declares table name.
@Basic Specifies non-constraint fields explicitly.
@Embedded Specifies the properties of class or an entity whose value is an instance of an embeddable class.
@Id Specifies the property, use for identity (primary key of a table) of the class.
@GeneratedValue Specifies how the identity attribute can be initialized such as automatic, manual, or value taken from a sequence table.
@Transient Specifies the property that is not persistent, i.e., the value is never stored in the database.
@Column Specifies the column attribute for the persistence property.
@SequenceGenerator Specifies the value for the property that is specified in the @GeneratedValue annotation. It creates a sequence.
@TableGenerator Specifies the value generator for the property specified in the @GeneratedValue annotation. It creates a table for value generation.
@AccessType This type of annotation is used to set the access type. If you set @AccessType(FIELD), then access occurs Field wise. If you set @AccessType(PROPERTY), then access occurs Property wise.
@JoinColumn Specifies an entity association or entity collection. This is used in many- to-one and one-to-many associations.
@UniqueConstraint Specifies the fields and the unique constraints for the primary or the secondary table.
@ColumnResult References the name of a column in the SQL query using select clause.
@ManyToMany Defines a many-to-many relationship between the join Tables.
@ManyToOne Defines a many-to-one relationship between the join Tables.
@OneToMany Defines a one-to-many relationship between the join Tables.
@OneToOne Defines a one-to-one relationship between the join Tables.
@NamedQueries specifies list of named queries.
@NamedQuery Specifies a Query using static name. 1.6 JPA transaction 1.7 example Phase :create employee entity Attention:
.the entity class can’t define final
.It must use @Entity to declare
.The entity class must have one constructor which without parameters
.It can extends others Entity or non entity class vice versa
.It can’t have public attribute,should define to private and make getter an setter to exposure the class members
.As a POJO entity,The entity can’t implement others interface but if user to sent message the it can implements serialize interface
@Entity
@Table(name = "EMPLOYEEA")
public class EmployeeA { @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "DID",nullable = false)
private Integer eid;
@Column(name = "ENAME",nullable = false)
private Integer ename;
@Column(name = "SALARY",nullable = false)
private Integer salary;
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public Integer getEname() {
return ename;
}
public void setEname(Integer ename) {
this.ename = ename;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public EmployeeA() {
super();
// TODO Auto-generated constructor stub
}
public EmployeeA(Integer eid, Integer ename, Integer salary) {
super();
this.eid = eid;
this.ename = ename;
this.salary = salary;
}
} Create department entity
@Entity
@Table(name = "DEPARTMENTA")
public class DepartmentA { @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "DID",nullable = false)
private Integer did;
@Column(name = "DNAME",nullable = false)
private String dname;
@Column(name = "CATE",nullable = false)
private String cate; @OneToMany(cascade = CascadeType.REMOVE)
private List<EmployeeA> employee; public List<EmployeeA> getEmployee() {
return employee;
}
public void setEmployee(List<EmployeeA> employee) {
this.employee = employee;
}
public Integer getDid() {
return did;
}
public void setDid(Integer did) {
this.did = did;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getCate() {
return cate;
}
public void setCate(String cate) {
this.cate = cate;
} } Persistence.xml
<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="tutorialspoint_JPA_Eclipselink" transaction-type="RESOURCE_LOCAL">
<class>com.eclipselink.entity.example.DepartmentA</class>
<class>com.eclipselink.entity.example.EmployeeA</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.18.139:3306/stu"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.logging.level" value="FINE"/> <!-- -->
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
</properties>
</persistence-unit>
</persistence> test
public class JPATest { private static EntityManagerFactory managerFactory;
private static String jpa;
private static EntityManager entityManager; static {
Properties properties = new Properties();
InputStream inputStream = JPATest.class.getClassLoader()
.getResourceAsStream("JPA.properties"); try { properties.load(inputStream);
jpa = properties.getProperty("JAP");
System.err.println(jpa);
} catch (IOException e) {
e.printStackTrace();
} managerFactory = Persistence.createEntityManagerFactory(jpa);
entityManager = managerFactory.createEntityManager();
}
@Test
public void insert() {
entityManager.getTransaction().begin();
Student student = new Student();
student.setStudent_id();
student.setCourse("english");
student.setName("wangwu2");
student.setScore("");
entityManager.persist(student);
entityManager.getTransaction().commit(); entityManager.close();
managerFactory.close();
}
@Test
public void update() {
entityManager.getTransaction().begin();
Student student = entityManager.find(Student.class, );
System.err.println(student);
student.setScore("");
entityManager.getTransaction().commit();
System.err.println(student); entityManager.close();
managerFactory.close();
} @Test
public void del() {
entityManager.getTransaction().begin(); Student student = entityManager.find(Student.class, );
System.err.println(student);
entityManager.remove(student);
entityManager.getTransaction().commit();
System.err.println(student); entityManager.close();
managerFactory.close();
} @Test
public void getAll() {
Query query = entityManager.createQuery("Select s from Student s"); // entityManager.getTransaction().begin(); // List<Student> list = (List<Student>)query.getResultList();
List<Student> list = query.getResultList(); for(Student student : list) {
System.err.println(student);
}
// entityManager.getTransaction().commit(); entityManager.close();
managerFactory.close();
} JPA Entity life cycle manager by Entity Manager and the Entity Manager is an instance of javax.persistence.EntityManager Reference:
https://www.tutorialspoint.com/jpa/jpa_quick_guide.htm
2THE JPA advantage
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. 2.1 advantage
JPA support OOP features,for example extends and polymorphic and so on
JPA and Hibernate have a complete ORM solution.
JPA provides support for container-level features,for example support container level transactions, such as large data sets, transactions, concurrency, and so on 2.3 jap and hibernate
In short JPA is a specification,not a framework.but hibernate is a framework which is implement JPA 3THE difference JPA and Mybatis
JPA is a specification not a framework,Mybatis is a framework.The hibernate implement JPA standards and specifications.So we can use Hibernate compared to mybatis. First :Hibernate is a more powerful and advanced framework. After all, at the level of Java code, most of SQL is omitted, instead of data manipulation in relational database. MyBatis is a persistent layer framework that can flexibly write SQL statements and map the input and query results of SQL into a POJOs. So, on the surface, hibernate is more convenient and more automated, and MyBatis is more flexible in the writing of Sql statements.

jpa summary的更多相关文章

  1. Spring Data JPA 多个实体类表联合视图查询

    Spring Data JPA 查询数据库时,如果两个表有关联,那么就设个外键,在查询的时候用Specification创建Join 查询便可.但是只支持左连接,不支持右连接,虽说左右连接反过来就能实 ...

  2. Java Spring Boot VS .NetCore (四)数据库操作 Spring Data JPA vs EFCore

    Java Spring Boot VS .NetCore (一)来一个简单的 Hello World Java Spring Boot VS .NetCore (二)实现一个过滤器Filter Jav ...

  3. Why I don't want use JPA anymore

    转自:https://dev.to/alagrede/why-i-dont-want-use-jpa-anymore-fl Great words for what is considered by ...

  4. Spring Data JPA中的动态查询 时间日期

    功能:Spring Data JPA中的动态查询 实现日期查询 页面对应的dto类private String modifiedDate; //实体类 @LastModifiedDate protec ...

  5. 如何让jpa 持久化时不校验指定字段

    源文:https://www.toocruel.net/jpa-validate/ 怎么让jpa 持久化时不校验指定字段 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥 ...

  6. [转] JPA 2.0 with EclipseLink - 教程

    原文: http://www.vogella.com/articles/JavaPersistenceAPI/article.html Lars Vogel Version 2.2 Copyright ...

  7. Summary of Critical and Exploitable iOS Vulnerabilities in 2016

    Summary of Critical and Exploitable iOS Vulnerabilities in 2016 Author:Min (Spark) Zheng, Cererdlong ...

  8. 快速搭建springmvc+spring data jpa工程

    一.前言 这里简单讲述一下如何快速使用springmvc和spring data jpa搭建后台开发工程,并提供了一个简单的demo作为参考. 二.创建maven工程 http://www.cnblo ...

  9. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

随机推荐

  1. WC游记

    第一次来WC,感觉这种集训真吼啊 day0 火车上快速补习了莫队,和AC自动姬,AC自动姬以前就会写只不过太久没写忘了我会了= = 莫队只是学习了做法,还没有做过题…… 本来想再复习一下后缀数组,然后 ...

  2. ASP.NET 4.0尚未在 Web 服务器上注册

    ASP.NET 4.0尚未在 Web 服务器上注册 解决方法 使用VS2010创建web应用程序时出现如下提示ASP.NET 4.0尚未在 Web 服务器上注册.为了使网站正确运行,可能需要手动将 W ...

  3. drill 集成开源s3 存储minio

    drill 支持s3数据的查询,同时新版的通过简单配置就可以实现minio 的集成 测试使用docker 运行drill 参考 https://www.cnblogs.com/rongfenglian ...

  4. Monocular 集成harbor helm 仓库

      harbor 已经支持了helm 仓库(使用chartmuseum),Monocular 是一个不错的helm 仓库可视化工具 测试Monocular集成harbor 私服功能 使用docker- ...

  5. Javascript 在严格模式下禁止指向 this

    如下代码, f() 输出的是 false,而 f2() 输出的是 true. 这是因为 f2 在严格模式下禁止 this 指向全局,所以 this 是 undefined, !this 当然是 tru ...

  6. postman环境变量的设置

    相同的api接口因为部署环境不同,分为test和fromal 不仅重复,还容易出错 下面来介绍一下Postman的一个小技巧来解决这种问题: 设置环境变量 Tips: 不是在OS中设置环境变量哦   ...

  7. module.exports用法

    module.exports 对象是由模块系统创建的.在我们自己写模块的时候,需要在模块最后写好模块接口,声明这个模块对外暴漏声明内容,module.exports提供了暴漏接口的方法. 1.返回一个 ...

  8. ML(3): 贝叶斯方法

    对于分类问题,我们每个人每天都在执行分类操作,只是我们没有意识到罢了.例如,当你看到一个陌生人,你的脑子下意识判断TA是男是女:你可能经常会走在路上对身旁的朋友说“这个人一看就很有钱.那边有个非主流” ...

  9. MySql检测阻塞,锁等待sql

    ------------ 1分钟内产生binlog大小计算 select @a1:=VARIABLE_VALUE as a1from information_schema.GLOBAL_STATUSw ...

  10. Python网络爬虫-Scrapy框架

    一.简介 Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适. 二.使用 1.创建sc ...