Introduction to JPA and build HelloWorld (with code to download)

Scenes

Before learning JPA at first to understand the relationship with the major JDBC database.

Long before there have been many databases such as Mysql, Oracle, SqlServer, DB2 and so on. This leads to the application you want to connect to which database API which will use the database.

So JDBC appeared, we define a set of specifications, JDBC calls by the application, and then call the required database.

 

 

Note:

Blog home page:
https://blog.csdn.net/badao_liumang_qizhi
public concern number of
programs overbearing ape
acquisition-related programming e-books, tutorials and push for free download.

achieve

What is JPA

Java Persistence API: The API for object persistence

Java EE5.0 platform standard ORM specification, enabling application in a uniform way to access persistence layer.

 

 

Relations JPA and Hibernate

1.JPA hibernate is an abstract, analogous to the relationship between JDBC and the JDBC driver.

2.JPA is the norm, the JPA ORM specification is a kind of nature, not an ORM framework. Because JPA ORM implementation does not provide, it just developed a number of standards, offer programming API interface, but the specific realization by ORM vendor implementation.

3.Hibernate is achieved: Hibernate as ORM framework in addition, it is also a realized JPA

JPA advantage

Standardization: to provide the same API, which ensures that after minor modifications can be able to run at different JPA framework for the development of enterprise applications based on the JPA.
Easy to use, easy integration: One of the main goals of the JPA is to provide a simpler programming model to create entities and create a Java class in the JPA framework as simple, just use javax.persistence.Entity annotate; JPA framework and interfaces also very simple,
comparable to JDBC query capabilities: JPA query language is object-oriented, JPA defines a unique JPQL, and can support batch updates and modify, JOIN, GROUP BY, HAVING and so usually only the SQL to be able to offer advanced query features, and even be able to support sub-queries.
Supports object-oriented advanced features: JPA can support advanced object-oriented features such as inheritance between classes, the complex relationships between the classes, and polymorphism, maximize the use of object-oriented model

3 including technical aspects of JPA

ORM mapping metadata: JPA supports two forms of metadata and the XML JDK 5.0 annotations, metadata that describes the relationship between the object and the mapping table, the frame whereby the entity object persisted to the database tables. 
The JPA API: used to manipulate physical objects, perform CRUD operations, the framework to do everything in the background, freed developers from the tedious JDBC and SQL code. 
Query Language (JPQL): This is a very important aspect of a persistent operations, rather than object-oriented database query language for query data, and specific procedures to avoid tight coupling of SQL.

Build HelloWorld

Open Eclipse-File-New JPA Project

 

 

Click Next

 

 

To select the Target runtime here for their jdk, and JPA Version, here is 2.0, then click next and then click next

 

 

First came to this page will not have EclipseLink, click the Download button on the right

 

 

Click next to select the specified version download, here chose EclipseLink2.5.2

下载完成点击Finish后项目结构如下

 

 

会自动生成一个persistence.xml

加入依赖

在项目下新建lib目录,然后加入相关jar包

 

 

修改配置文件

双击打开上面的persistnece.xml,选择Connection视图,然后选择Transaction Type 为Resource Local

然后依次配置好数据库的驱动等,其中URL中jpa对应的就是数据库名。

 

 

然后保存,使用Source视图查看,此时在properties下就会有如下代码

<properties>
 <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
 <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
 <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
 <property name="javax.persistence.jdbc.user" value="root"/>
 <property name="javax.persistence.jdbc.password" value="123"/>  
</properties>

 

然后再在配置文件中加入Hibernate相关的配置信息。

 

 <property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value= "update"/>

 

新增实体类 

在src下新建包com.badao.jpa.helloworld

包下新建实体类Customer,通过添加注解的方式完成实体类到数据库的映射。

1.在类名上添加@Entity表明是实体类。

2.在类名上添加@Table注解,并使用name属性与数据库中的表名相对应。

3.在主键ID的get方法上使用@Id声明是主键,并使用@GeneratedValue注解声明主键策略。

4.在某些实体类属性名与数据库列名不对应的属性的get方法上要使用@Column注解进行映射。

package com.badao.jpa.helloworld;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="JPA_CUSTOMERS")
public class Customer {
 
 
 private Integer id;
 
 private String lastName;

 private String email;
 
 private int age;
 
 @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 
 @Column(name="LAST_NAME")
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 

}

 

添加完实体类后还要回到配置文件中添加一行配置

<class>com.badao.jpa.helloworld.Customer</class>

 

完整配置文件代码

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
 <persistence-unit name="HelloJPA" transaction-type="RESOURCE_LOCAL">
  
  <!-- 添加持久化类 -->
  <class>com.badao.jpa.helloworld.Customer</class>
  <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
   <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
   <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
   <property name="javax.persistence.jdbc.user" value="root"/>
   <property name="javax.persistence.jdbc.password" value="523627"/>
   
   <!-- 配置 JPA 实现产品的基本属性. 配置 hibernate 的基本属性 -->
   <property name="hibernate.format_sql" value="true"/>
   <property name="hibernate.show_sql" value="true"/>
   <property name="hibernate.hbm2ddl.auto" value="update"/>
  </properties>
 </persistence-unit>
</persistence>

 

新建表

打开数据库jpa并新建表jpa_customers,设计字段如下

 

 

 

新建启动类

在包下新建Main类,然后编写main方法

package com.badao.jpa.helloworld;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class Main {

public static void main(String[] args) {
  
  //1. 创建 EntitymanagerFactory  要与配置文件中一致
  String persistenceUnitName = "HelloJPA";
  
    
  EntityManagerFactory entityManagerFactory = 
    Persistence.createEntityManagerFactory(persistenceUnitName);
        
  //2. 创建 EntityManager. 类似于 Hibernate 的 SessionFactory
  EntityManager entityManager = entityManagerFactory.createEntityManager();
  
  //3. 开启事务
  EntityTransaction transaction = entityManager.getTransaction();
  transaction.begin();
  
  //4. 进行持久化操作
  Customer customer = new Customer();
  customer.setAge(12);
  customer.setEmail("[email protected]");
  customer.setLastName("Badao");
  
  
  entityManager.persist(customer);
  
  //5. 提交事务
  transaction.commit();
  
  //6. 关闭 EntityManager
  entityManager.close();
  
  //7. 关闭 EntityManagerFactory
  entityManagerFactory.close();
 }
}

 

然后运行main方法

 

 

然后刷新数据库中的数据 


 

 

 

示例代码下载

关注公众号:

霸道的程序猿

回复:

HelloJPA

Guess you like

Origin www.cnblogs.com/badaoliumangqizhi/p/12016153.html