Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Understand java persistence API

2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "understanding java persistence API". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "understanding java persistence API".

PA,Java Persistence API is an official Java persistence specification proposed by Sun. It provides Java developers with an object / association mapping tool to manage relational data in Java applications. Its main purpose is to simplify the existing persistence development work and integrate ORM technology.

ORM: automatically persists objects in a program to a relational database by using metadata that describes the mapping between the object and the database. The essence is to convert data from one form to another.

At the same time, it also ends the situation of separate ORM frameworks such as Hibernate, TopLink and so on. JPA fully absorbs ORM frameworks such as Hibernate and TopLink. It is easy to use and has strong scalability.

Note: JPA is not a new ORM framework, its emergence is only used to standardize the existing ORM technology, it can not replace the existing ORM framework such as Hibernate, on the contrary, when using JPA development, we will still use these ORM frameworks, but the applications developed at this time no longer rely on a persistence provider. The application can run in any JPA environment without modifying the code, and it can really achieve low-coupling, extensible program design. Similar to JDBC, before the advent of JDBC, our program was programmed against the feature database API, but now we only need to program against JDBC API so that we can switch to other databases without changing the code.

JPA is a set of specifications, not a set of products. Hibernate is a set of products, if these products implement the JPA specification, then we can call them JPA implementation products. Using JPA, we can free our application from Hibernate, so now the question is: how to use JPA to develop?

Are you ready? let's get down to business. Take off!

First of all, let's take a look at the general introduction of this article.

How do you know how much practical information there is in this article without a catalogue?

Previous development model

What is JPA?

What problem did JPA solve?

The first HelloWord program of JPA

Explain the configuration file in detail

Commonly used comments

One-on-one problem

One-to-many problem

Many-to-many problem

Common methods in JPA

State of objects in JPA

Points for attention

Isn't it clear, what? Let's not get into the text, here we go, let's make arrangements, one by one:

Review previous development models

In the past, when we developed our DAO layer, we either used Hibernate or iBatis, dbutils, toplink.

Requirements: suppose that the implementation of DAO version 1.0 of the current product uses Hibernate, and now the boss requires that the DAO layer be replaced with TopLink

According to the current solution, the entire DAO layer needs to be rewritten, which consumes manpower and material resources and increases the cost.

Is there a plan? This solution is that if we need to change the ORM framework, our entire DAO layer does not need to change, just need to change the configuration file?

As a result, JPA technology was born.

What is JPA?

JPA is actually a set of specifications issued by sun Company. The purpose of this set of specifications is to solve the dominant problem of ORM framework in the market.

JPA is a set of specifications, as long as our ORM framework implements this set of specifications, then when using this ORM framework, we do not need to face the API of a certain ORM product for programming, but a unified JPA-oriented programming. at this time, even if your ORM product changes, then your DAO level to JPA programming code does not need to change.

What problem did JPA solve?

JPA unifies the API for ORM framework to access databases.

JPA solves the dominant problem of ORM framework.

The first HelloWorld program of JPA

Guide package

Write a configuration file

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"

Version= "2.1" >

Copy and write Java entities and comments

@ Table (name= "t_user") / / sets the table name corresponding to the object of the current class

@ Entity / / indicates that the current class is a persistent entity

Public class User {

@ Id / / this indicates that the current field is the primary key

@ GeneratedValue (strategy=GenerationType.IDENTITY) / / this represents the primary key generation strategy (self-growing)

@ Column (name= "uId")

Private int uId

@ Column (name= "userName") / / column name

Private String userName

@ Column (name= "password")

Private String password

}

Copy test

@ Test

Public void testHelloWorld () throws Exception {

/ / first step: create an entity-managed factory

EntityManagerFactory ef=Persistence.createEntityManagerFactory ("hibernateJPA")

/ / create the manager of the entity through the factory

EntityManager em=ef.createEntityManager ()

/ / step 3: start the transaction

Em.getTransaction () .begin ()

/ / operate business logic

User user=new User ()

User.setUserName (Asahi)

User.setPassword ("123")

/ / Save the user entity to the database

Em.persist (user)

/ / commit transaction

Em.getTransaction () .commit ()

/ / close the manager

Em.close ()

Ef.close ()

}

Copy the detailed configuration file

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"

Version= "2.1" >

Copy commonly used annotation thread pool techniques

Table: indicates the name of the table in the database corresponding to the current entity

@ Entity: indicates that the current entity is a persistent entity

Id: this indicates that the current property is a primary key

@ GeneratedValue: primary key generation strategy

Strategy=GenerationType.IDENTITY: this represents the self-growth of the primary key

Strategy=GenerationType.AUTO: use the table to generate the primary key of the target table

Strategy=GenerationType.SEQUENCE: use sequences to generate primary keys

The name of the column of the database table corresponding to the attribute of @ Column:jAVA

Name: first name

Length: indicates the length of the field

Nullable=false: this means that it cannot be null.

Unique=true: whether it is unique or not

@ Transient: the current field does not correspond to columns in the database

@ Enumerated: indicates whether to enumerate the mapping in the database using subscripts or strings

EnumType.STRING: represents the display as a string

EnumType.ORDINAL: indicates that enumerations are displayed in the following form in the data

@ Lob: large text represented when decorating the String type

When you modify byte [], it means that binary is stored.

Copy the one-to-one problem

Demand: one person corresponds to an ID card, and an ID card corresponds to only one person.

ID card-> person

An one-to-one relationship

Code demonstration:

Declare the IdCard class:

@ Entity

@ Table

Public class IdCard {

@ Id

Private String cardNum

Private Date startTime

Private Date endTime

/ / an ID card corresponds only to one person.

@ OneToOne (cascade=CascadeType.ALL,fetch=FetchType.LAZY)

@ JoinColumn (name= "pId") / / this represents adding a column that maps the Id in the object below.

Private People people

}

Copy the declaration People class:

@ Entity

@ Table

Public class People {

@ Id

@ GeneratedValue (strategy=GenerationType.IDENTITY)

Private int pId

Private String pName

Private String pTel

/ / A person corresponds to an ID card

/ / which party with mappedBy configured in the association relationship does not have the right to maintain the other party

The value of / / mappedBy is the name that the current class declares in the following object

OneToOne (mappedBy= "people", cascade=CascadeType.ALL)

Private IdCard idCard

}

Copy the test:

@ Test

Public void testHelloWorld () throws Exception {

EntityManager entityManager=JPAUtils.getEntityManager ()

IdCard idCard=new IdCard ()

IdCard.setCardNum ("510. X")

IdCard.setStartTime (new Date ())

IdCard.setEndTime (new Date ())

People people=new People ()

People.setpName (Xiaoyu)

People.setpTel ("1234566")

IdCard.setPeople (people)

EntityManager.persist (idCard)

JPAUtils.close ()

}

Copy the one-to-many problem

Demand: correspondence between departments and employees

Department-> employee

One-to-many relationship

Code demonstration:

Declare the department object:

@ Entity

@ Table

Public class Dept {

@ Id

@ GeneratedValue (strategy=GenerationType.IDENTITY)

Private int dId

Private String dName

Private String dDes

/ / there are multiple employees in a department

@ OneToMany (cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy= "dept")

Private Set emps

}

Copy the declared employee object:

@ Entity

@ Table

Public class Employee {

@ Id

@ GeneratedValue (strategy=GenerationType.IDENTITY)

Private int empId

Private String empName

@ ManyToOne (cascade=CascadeType.ALL,fetch=FetchType.LAZY)

@ JoinColumn (name= "dId")

Private Dept dept

}

Copy the test:

@ Test

Public void testOne2Many () throws Exception {

EntityManager entityManager=JPAUtils.getEntityManager ()

Employee emp=new Employee ()

Emp.setEmpName ("Xiao Na")

Dept dept=new Dept ()

Dept.setdName ("R & D Department")

Dept.setdDes ("specializing in development")

Emp.setDept (dept)

EntityManager.persist (emp)

JPAUtils.close ()

}

Copy the many-to-many problem

Needs: a student can be taught by multiple teachers, and a teacher can also teach multiple students

Student-> teacher one-to-many

Teacher-> student one-to-many

The ultimate relationship between teachers and students many-to-many relationship

Code demonstration:

Write teacher entities:

@ Entity

@ Table

Public class Teacher {

@ Id

Private String tNum

Private String tName

@ ManyToMany (cascade=CascadeType.ALL,fetch=FetchType.LAZY)

@ JoinTable (name= "t_teacher_student"

JoinColumns=@JoinColumn (name= "tNum"), / / maps the primary key of the current class

InverseJoinColumns= {@ JoinColumn (name= "stuNum")}) / / maps the primary key of the other table

Private Set students

}

Copy and write the student entity:

@ Entity

@ Table

Public class Student {

@ Id

Private int stuNum

Private String stuName

Private int age

@ ManyToMany (cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy= "students")

Private Set teachers

}

Copy the test:

@ Test

Public void testMany2Many () throws Exception {

EntityManager em=JPAUtils.getEntityManager ()

Teacher teacher=new Teacher ()

Teacher.settName (Xiaoyu)

Teacher.settNum ("007")

Set students=new HashSet ()

Student student=new Student ()

Student.setAge (18)

Student.setStuName (rookie)

Student.setStuNum (100)

Student student1=new Student ()

Student1.setAge (19)

Student1.setStuName ("Xiao Na")

Student1.setStuNum (1000)

Student student2=new Student ()

Student2.setAge (20)

Student2.setStuName ("Little Black")

Student2.setStuNum (10000)

Students.add (student)

Students.add (student1)

Students.add (student2)

Teacher.setStudents (students)

Em.persist (teacher)

JPAUtils.close ()

}

Copy the common methods in JPA

Code demonstration:

Common methods:

Public void testMethod () throws Exception {

EntityManager entityManager=JPAUtils.getEntityManager ()

User user= new User ()

User.setUserName (Little Grey)

User.setuId (1)

/ / method of adding data

/ / entityManager.persist (user)

/ / query data

/ / User user2=entityManager.find (User.class,1)

/ / this is written as a HQL statement

/ / Query query=entityManager.createQuery ("from User")

/ / List list=query.getResultList ()

/ / the following method has a primary key value, so modify it and insert it without the primary key value.

/ / entityManager.merge (user)

/ * the query created is the local SQL

Query query=entityManager.createNativeQuery ("select * from user")

List list=query.getResultList (); * /

/ / it is generally used to obtain the latest data in a query.

/ / entityManager.refresh (user)

User user2=entityManager.find (User.class,1)

EntityManager.remove (user2)

/ / System.out.println (list)

JPAUtils.close ()

}

Copy the state of objects in JPA

Status of the object:

New state: User user = new User (); it has nothing to do with the database or memory, and the object is just the state after it is new.

Managed state: the object state after the object calls find persist refresh merge or query is called managed state. The data in managed state is managed by entityManager, and the memory corresponds to the data in the database. At this time, if you change the data in memory and submit it, then the data will be synchronized with the database.

Free state: the object is in a free state for the period of time after the current object calls the clear method and before the close method. Clear: indicates a clear relationship between memory and database data

Delete state: this state of the object after the current object close is called the delete state

Points for attention

If the table name is not written, the default is the class as the table name.

Column does not write, and the column name of the table is the property name of the class.

@ GeneratedValue is followed by auto by default.

Thank you for your reading, the above is the content of "understanding java persistence API". After the study of this article, I believe you have a deeper understanding of the problem of understanding java persistence API, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report