1. JPA
  2. Prepared by: John Tan March,
  3. Contents
  4. what is JPA
  5. 1.1 Introduction
  6. 1.2 architectrue
  7. 1.3 jpa-EntityManagers and Relationship
  8. 1.4 jpa-ORM Componments
  9. 1.5 jpa-annotations
  10. 1.6 a simple example
  11. Where to use JPA
  12. 2.1 adventage
  13. 2.2 Relationship of JPA and Hibernate
  14. 2.3 example of JPA+Hibernate+spring
  15.  
  16. Difference between JPA and Mybatis
  17.  
  18. 1THE DESCRIPTION OF JPA
  19. .1Introduction
  20. 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)
  21. 1.2 architecture
  22. EntityManageFactory:This is factory of EntityManager.It creates and manager multiple EntityManager instance.
  23. EntityManager:It is an Interface, it manages the persistence operations on objects. It works like factory for Query instance.
  24.  
  25. Entity:Entities are the persistence objects, stores as records in the database.
  26.  
  27. Query:This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.
  28.  
  29. EntityTransaction:It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
  30.  
  31. Persistence:This class contain static methods obtain EntityManagerFactory instance.
  32.  
  33. 1.3 Jpa class relationship
  34.  
  35. The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances.
  36. The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance.
  37. The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance.
  38. The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities.
  39. 1.4 Orm components
  40. ORM (Object Relational Mapping) is a programming ability to covert data from object type to relational type and vice versa.
  41. ORM Advantage:
  42. Idiomatic persistence : It enables you to write the persistence classes using object oriented classes.
  43. High Performance : It has many fetching techniques and hopeful locking techniques.
  44. Reliable : It is highly stable and eminent. Used by many industrial programmers.
  45.  
  46. 1.5 Jpa annotations
  47. 1.5.1Some annotations
  48. @Entity declares the class as an entity.It is must to declares
  49.  
  50. @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
  51.  
  52. @Id Specifies the property, use for identity (primary key of a table) of the class.
  53.  
  54. @OneToOne,@ManyToMany,@OneToMany,@ManyToOne, if you want to implements cascading delete
  55. You must set cascade = CascadeType.REMOVE and the CascadeType has five attribute:
  56.  
  57. CascadeType.ALL : It is contain all methods
  58. 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 cant delete B records,It will be throws a Exception
  59. CascadeType.PERSIST : cascade save,we can add records in A Object then B Object will increase with A add records
  60.  
  61. CascadeType.MERGE:With the A Object had change then B Object has change
  62.  
  63. CascadeType.REFRESH : cascade refresh
  64.  
  65. @ManyToMany,@OneToMany :if we use those annotations that we must be target a entity,like
  66. @OneToMany( targetEntity=Employee.class )
  67. @OneToMany( targetEntity=Employee.class )
  68.  
  69. 1.5.2Automatic generation of JPA entity identify
  70. 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.
  71.  
  72. Container automatic generation entity identify
  73. Use the database automatic increment to automatic generation entity identify
  74. According the database sequence technology
  75. Use the database table field to generation entity identify
  76.  
  77. We can use these annotations @GenerateValue,@SequenceGenerator and @TableGenerator all the these annotations are under the package javax.persistence.*
  78. 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.
  79.  
  80. the @GenerateValue have two attributes are strategy and generator.
  81.  
  82. Strategy is the enumeration of GenerationType
  83.  
  84. GenerationType.AUTO is OpenJPA container automatic generation entity identify,this is default
  85. GenertaionType.INENTITY is using database auto increment field as the new increase entity unique value
  86. GenerationType.SEQUENCE which is define using the sequence number of database as assign unique value to newly entity object as an entity sign
  87. GenerationType.TABLE is using database one filed to record entity object sign,by this filed increase for newly entity object to assign unique value
  88.  
  89. Annotation Description
  90. @Entity Declares the class as an entity or a table.
  91. @Table Declares table name.
  92. @Basic Specifies non-constraint fields explicitly.
  93. @Embedded Specifies the properties of class or an entity whose value is an instance of an embeddable class.
  94. @Id Specifies the property, use for identity (primary key of a table) of the class.
  95. @GeneratedValue Specifies how the identity attribute can be initialized such as automatic, manual, or value taken from a sequence table.
  96. @Transient Specifies the property that is not persistent, i.e., the value is never stored in the database.
  97. @Column Specifies the column attribute for the persistence property.
  98. @SequenceGenerator Specifies the value for the property that is specified in the @GeneratedValue annotation. It creates a sequence.
  99. @TableGenerator Specifies the value generator for the property specified in the @GeneratedValue annotation. It creates a table for value generation.
  100. @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.
  101. @JoinColumn Specifies an entity association or entity collection. This is used in many- to-one and one-to-many associations.
  102. @UniqueConstraint Specifies the fields and the unique constraints for the primary or the secondary table.
  103. @ColumnResult References the name of a column in the SQL query using select clause.
  104. @ManyToMany Defines a many-to-many relationship between the join Tables.
  105. @ManyToOne Defines a many-to-one relationship between the join Tables.
  106. @OneToMany Defines a one-to-many relationship between the join Tables.
  107. @OneToOne Defines a one-to-one relationship between the join Tables.
  108. @NamedQueries specifies list of named queries.
  109. @NamedQuery Specifies a Query using static name.
  110.  
  111. 1.6 JPA transaction
  112.  
  113. 1.7 example
  114.  
  115. Phase :create employee entity
  116.  
  117. Attention:
  118. .the entity class cant define final
  119. .It must use @Entity to declare
  120. .The entity class must have one constructor which without parameters
  121. .It can extends others Entity or non entity class vice versa
  122. .It cant have public attribute,should define to private and make getter an setter to exposure the class members
  123. .As a POJO entity,The entity cant implement others interface but if user to sent message the it can implements serialize interface
  124. @Entity
  125. @Table(name = "EMPLOYEEA")
  126. public class EmployeeA {
  127.  
  128. @Id
  129. @GeneratedValue(strategy = GenerationType.AUTO)
  130. @Column(name = "DID",nullable = false)
  131. private Integer eid;
  132. @Column(name = "ENAME",nullable = false)
  133. private Integer ename;
  134. @Column(name = "SALARY",nullable = false)
  135. private Integer salary;
  136. public Integer getEid() {
  137. return eid;
  138. }
  139. public void setEid(Integer eid) {
  140. this.eid = eid;
  141. }
  142. public Integer getEname() {
  143. return ename;
  144. }
  145. public void setEname(Integer ename) {
  146. this.ename = ename;
  147. }
  148. public Integer getSalary() {
  149. return salary;
  150. }
  151. public void setSalary(Integer salary) {
  152. this.salary = salary;
  153. }
  154. public EmployeeA() {
  155. super();
  156. // TODO Auto-generated constructor stub
  157. }
  158. public EmployeeA(Integer eid, Integer ename, Integer salary) {
  159. super();
  160. this.eid = eid;
  161. this.ename = ename;
  162. this.salary = salary;
  163. }
  164. }
  165.  
  166. Create department entity
  167. @Entity
  168. @Table(name = "DEPARTMENTA")
  169. public class DepartmentA {
  170.  
  171. @Id
  172. @GeneratedValue(strategy = GenerationType.AUTO)
  173. @Column(name = "DID",nullable = false)
  174. private Integer did;
  175. @Column(name = "DNAME",nullable = false)
  176. private String dname;
  177. @Column(name = "CATE",nullable = false)
  178. private String cate;
  179.  
  180. @OneToMany(cascade = CascadeType.REMOVE)
  181. private List<EmployeeA> employee;
  182.  
  183. public List<EmployeeA> getEmployee() {
  184. return employee;
  185. }
  186. public void setEmployee(List<EmployeeA> employee) {
  187. this.employee = employee;
  188. }
  189. public Integer getDid() {
  190. return did;
  191. }
  192. public void setDid(Integer did) {
  193. this.did = did;
  194. }
  195. public String getDname() {
  196. return dname;
  197. }
  198. public void setDname(String dname) {
  199. this.dname = dname;
  200. }
  201. public String getCate() {
  202. return cate;
  203. }
  204. public void setCate(String cate) {
  205. this.cate = cate;
  206. }
  207.  
  208. }
  209.  
  210. Persistence.xml
  211. <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">
  212. <persistence-unit name="tutorialspoint_JPA_Eclipselink" transaction-type="RESOURCE_LOCAL">
  213. <class>com.eclipselink.entity.example.DepartmentA</class>
  214. <class>com.eclipselink.entity.example.EmployeeA</class>
  215. <properties>
  216. <property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.18.139:3306/stu"/>
  217. <property name="javax.persistence.jdbc.user" value="root"/>
  218. <property name="javax.persistence.jdbc.password" value=""/>
  219. <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
  220. <property name="eclipselink.logging.level" value="FINE"/>
  221.  
  222. <!-- -->
  223. <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
  224. </properties>
  225. </persistence-unit>
  226. </persistence>
  227.  
  228. test
  229. public class JPATest {
  230.  
  231. private static EntityManagerFactory managerFactory;
  232. private static String jpa;
  233. private static EntityManager entityManager;
  234.  
  235. static {
  236. Properties properties = new Properties();
  237. InputStream inputStream = JPATest.class.getClassLoader()
  238. .getResourceAsStream("JPA.properties");
  239.  
  240. try {
  241.  
  242. properties.load(inputStream);
  243. jpa = properties.getProperty("JAP");
  244. System.err.println(jpa);
  245. } catch (IOException e) {
  246. e.printStackTrace();
  247. }
  248.  
  249. managerFactory = Persistence.createEntityManagerFactory(jpa);
  250. entityManager = managerFactory.createEntityManager();
  251. }
  252. @Test
  253. public void insert() {
  254. entityManager.getTransaction().begin();
  255. Student student = new Student();
  256. student.setStudent_id();
  257. student.setCourse("english");
  258. student.setName("wangwu2");
  259. student.setScore("");
  260. entityManager.persist(student);
  261. entityManager.getTransaction().commit();
  262.  
  263. entityManager.close();
  264. managerFactory.close();
  265. }
  266. @Test
  267. public void update() {
  268. entityManager.getTransaction().begin();
  269. Student student = entityManager.find(Student.class, );
  270. System.err.println(student);
  271. student.setScore("");
  272. entityManager.getTransaction().commit();
  273. System.err.println(student);
  274.  
  275. entityManager.close();
  276. managerFactory.close();
  277. }
  278.  
  279. @Test
  280. public void del() {
  281. entityManager.getTransaction().begin();
  282.  
  283. Student student = entityManager.find(Student.class, );
  284. System.err.println(student);
  285. entityManager.remove(student);
  286. entityManager.getTransaction().commit();
  287. System.err.println(student);
  288.  
  289. entityManager.close();
  290. managerFactory.close();
  291. }
  292.  
  293. @Test
  294. public void getAll() {
  295. Query query = entityManager.createQuery("Select s from Student s");
  296.  
  297. // entityManager.getTransaction().begin();
  298.  
  299. // List<Student> list = (List<Student>)query.getResultList();
  300. List<Student> list = query.getResultList();
  301.  
  302. for(Student student : list) {
  303. System.err.println(student);
  304. }
  305. // entityManager.getTransaction().commit();
  306.  
  307. entityManager.close();
  308. managerFactory.close();
  309. }
  310.  
  311. JPA Entity life cycle manager by Entity Manager and the Entity Manager is an instance of javax.persistence.EntityManager
  312.  
  313. Reference:
  314. https://www.tutorialspoint.com/jpa/jpa_quick_guide.htm
  315. 2THE JPA advantage
  316. 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.
  317.  
  318. 2.1 advantage
  319. JPA support OOP features,for example extends and polymorphic and so on
  320. JPA and Hibernate have a complete ORM solution.
  321. JPA provides support for container-level features,for example support container level transactions, such as large data sets, transactions, concurrency, and so on
  322.  
  323. 2.3 jap and hibernate
  324. In short JPA is a specification,not a framework.but hibernate is a framework which is implement JPA
  325.  
  326. 3THE difference JPA and Mybatis
  327. 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.
  328.  
  329. 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. (1)json和pickle序列化模块

    json 和pickle 模块 json和pickle模块下都有4个功能 dumps  <---> loads  (序列化 <--->反序列化) dump <---> ...

  2. bat中的“多线程”处理代码

    大家都知道,批处理中运行的都是一步步单进程执行, 但如果进程执行比较慢,如PING一个不通的IP地址,那就会大大影响批处理程序的执行效率. 如下内容将简单举例,在WINDOWS下使用批处理做多进程并发 ...

  3. Oracle 补丁体系 及 opatch 工具 介绍

    一. CPU(Critical Patch Update) 一个CPU内包含了对多个安全漏洞的修复,并且也包括相应必需的非安全漏洞的补丁.CPU是累积型的,只要安装最新发布的CPU即可,其中包括之前发 ...

  4. JUC集合之 ConcurrentSkipListSet

    ConcurrentSkipListSet介绍 ConcurrentSkipListSet是线程安全的有序的集合,适用于高并发的场景. ConcurrentSkipListSet和TreeSet,它们 ...

  5. Java8 lam。。。表达式

    双冒号:相当于用了别人实现的方法,格式,类名::方法 Math::max等效于(a, b)->Math.max(a, b)String::startWith等效于(s1, s2)->s1. ...

  6. mysql 官方docker镜像使用教程

    首先是pull image,这里我拉取的是5.x版本最新版: docker pull mysql:5 拉下来以后大可以按照官方的说明无脑启动,但是外部无法访问,所以绑定端口:docker run -- ...

  7. WinForm 打开文件夹

    string path="c:\windows"; Process.Start("explorer.exe", path);

  8. fiddler抓包HTTPS请求

    fiddler抓包HTTPS请求 标签: fiddlerhttps抓包 2016-03-29 21:24 23293人阅读 评论(2) 收藏 举报  分类: 不登高山不知天之高也(1)  版权声明:本 ...

  9. bzoj1034 泡泡堂

    Description 第XXXX届NOI期间,为了加强各省选手之间的交流,组委会决定组织一场省际电子竞技大赛,每一个省的代表队由n名选手组成,比赛的项目是老少咸宜的网络游戏泡泡堂.每一场比赛前,对阵 ...

  10. 小峰mybatis(1) 处理clob,blob等。。

    一.mybatis处理CLOB.BLOB类型数据 CLOB:大文本类型:小说啊等大文本的:对应数据库类型不一致,有long等: BLOB:二进制的,图片:电影.音乐等二进制的: 在mysql中: bl ...