Spring Data Development Manual|How much do you need to know about Java Persistence API (JPA)?

JPA , Java Persistence API is the Java persistence specification officially proposed by Sun. It provides an object/association mapping tool for Java developers to manage relational data in Java applications. Its appearance is mainly to simplify the existing persistence development work and integrate ORM technology

ORM: By using metadata describing the mapping between objects and databases, the objects in the program are automatically persisted to the relational database. The essence is to transform data from one form to another.

At the same time, it also ended the situation where ORM frameworks such as Hibernate and TopLink worked independently. JPA is developed on the basis of fully absorbing Hibernate, TopLink and other ORM frameworks, and is easy to use and highly scalable.

Note: JPA is not a new ORM framework. Its appearance is only used to standardize the existing ORM technology. It cannot replace the existing ORM frameworks such as Hibernate. On the contrary, when developing with JPA, we will still use these ORM frameworks. It's just that the applications developed at this time no longer depend on a certain persistence provider. The application can be downloaded and run in any JPA environment without modifying the code, truly low coupling and extensible programming. Similar to JDBC, before the advent of JDBC, our program was programmed for the characteristic database API, but now we only need to program for the 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, go to the main topic, take off!

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

How do you know how many dry goods there are in this article without a catalog?

  • Previous development model

  • What is JPA

  • What problem does JPA solve

  • JPA's first HelloWord program

  • Detailed configuration file

  • Common annotations

  • One to one question

  • One-to-many problem

  • Many-to-many problem

  • Common methods in JPA

  • The state of objects in JPA

  • Precautions

Isn’t it clear, what? Without getting into the main text, here comes the arrangement, one by one:

Review the previous development model

When developing our DAO layer before, we either used Hibernate, or iBatis, dbutils, toplink

Requirements: Assume that the implementation of the 1.0 version of the DAO of the current product uses Hibernate, and the boss now 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 costs.

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

JPA technology is born

What is JPA

JPA is actually a set of specifications issued by sun company. The role of this set of specifications is to solve the unique problem of ORM framework in the market.

JPA is a set of specifications. As long as our ORM framework implements this set of specifications, when using this ORM framework, there is no need to program in the API of a certain ORM product, but to be unified for JPA For programming, even if your ORM product changes at this time, then your DAO layer-oriented code for JPA programming does not need to change

What problem does JPA solve

JPA unifies the ORM framework to access the database API

JPA solves the unique problem of ORM framework

JPA's first HelloWorld program

Guide package

Write configuration file

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
 version="2.1">
 <persistence-unit name="hibernateJPA" transaction-type="RESOURCE_LOCAL">
  <properties>
   <property name="hibernate.hbm2ddl.auto" value="update"></property>
   <property name="hibernate.show_sql" value="true"></property>
   <property name="hibernate.format_sql" value="true"></property>
   <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"></property>
   <property name="hibernate.connection.url" value="jdbc:mysql:///qianyu"></property>
   <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"></property>
   <property name="hibernate.connection.username" value="root"></property>
   <property name="hibernate.connection.password" value="root"></property>
  </properties>
 </persistence-unit>
 
</persistence>  

Write Java entities and annotations

@Table(name="t_user")     //设置当前的类的对象对应的表名字
@Entity                   //表示当前的这个类是一个持久化的实体
public class User {
 @Id                  //这个表示的是当前的字段是主键
 @GeneratedValue(strategy=GenerationType.IDENTITY)   //这个表示的是主键的生成策略(自增长)
 @Column(name="uId")
 private int uId;
 
 @Column(name="userName")   //列的名字
 private String userName;
 
 @Column(name="password")
 private String password;

}

test

@Test
 public void testHelloWorld() throws Exception {
  
  //第一步:创建实体管理的工厂
  EntityManagerFactory ef=Persistence.createEntityManagerFactory("hibernateJPA");
  //通过工厂创建实体的管理器
  EntityManager em=ef.createEntityManager();
  //第三步:开启事务
  em.getTransaction().begin();
  //操作业务逻辑
  
  User user=new User();
  user.setUserName("浅羽");
  user.setPassword("123");
  //保存用户实体到数据库
  em.persist(user);
  
  //提交事务
  em.getTransaction().commit();
  //关闭管理器
  em.close();
  ef.close();
 }

Detailed configuration file

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
 version="2.1">
    <!--
         persistence-unit:这个叫做持久化的单元   这个的作用就是配置 访问数据库的信息
         name:逻辑意义上可以随便写  但是一般情况下见名之意  这个一般情况下写JPA的实现产品的名字
         transaction-type:事务的类型
            RESOURCE_LOCAL:局部事务
            
                    事务的分类   
                         全局事务
                               举例:张三给李四转账(建设银行----中国银行)          
                         
                         局部事务
                               举例:所有的操作在同一个库里头执行          
                         
                         粗粒度事务
                              举例:能够对整个类或者方法体进行事务的管理           
            
                         细粒度事务    
                              举例:就是能够对某几行代码进行事务的管理                                  
    -->
 <persistence-unit name="hibernateJPA" transaction-type="RESOURCE_LOCAL">
  <properties>
   <property name="hibernate.hbm2ddl.auto" value="update"></property>
   <property name="hibernate.show_sql" value="true"></property>
   <property name="hibernate.format_sql" value="true"></property>
   <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"></property>
   <property name="hibernate.connection.url" value="jdbc:mysql:///qianyu"></property>
   <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"></property>
   <property name="hibernate.connection.username" value="root"></property>
   <property name="hibernate.connection.password" value="root"></property>
  </properties>
 </persistence-unit>
 
</persistence>  

Commonly used annotation thread pool technology

@Table:表示的是当前的实体对应的数据库中的表名字
@Entity:表示的是当前的实体是一个持久化的实体
@Id:这个表示当前的属性是一个主键
@GeneratedValue:主键的生成策略
strategy=GenerationType.IDENTITY:这个表示的是主键自增长
strategy=GenerationType.AUTO:使用表来生成目标表的主键
strategy=GenerationType.SEQUENCE:使用序列来生成主键
@Column:jAVA的属性对应的数据库表的列的名字
Name:名字
Length:表示的是字段的长度
nullable=false:这个表示的是不能为null
unique=true:是否是唯一的
@Transient :当前字段在数据库中不对应列
@Enumerated:表示的是枚举在数据库中的映射使用下标还是字符串
EnumType.STRING:表示的是以字符串的形式显示
EnumType.ORDINAL:表示枚举在数据中以下标的形式显示
@Lob:修饰String类型的时候 表示的大文本
       修饰byte[]的时候表示存储的是二进制

One to one question

Demand: one person corresponds to one ID card, and one ID card also corresponds to one person only

  • ID card----->person

  • One-to-one relationship

Code demo:

声明IdCard类

@Entity
@Table
public class IdCard {
 
 @Id
 private String cardNum;
  
 private Date startTime;
 
 private Date endTime;
 
 //一个身份证唯一的对应了一个人
 @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
 @JoinColumn(name="pId")     //这个表示的是添加一个列 这个列映射下面对象中的这个Id
 private People people;
}

声明People类

@Entity
@Table
public class People {
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int pId;
 
 private String pName;
 
 private String pTel;
 
 //一个人对应了一个身份证
 //在关联关系中 配置了mappedBy的哪一方没有权限维护另外一方
 //mappedBy的值就是当前的类在下面对象中声明的这个名字
 @OneToOne(mappedBy="people",cascade=CascadeType.ALL)
 private IdCard idCard;
}

测试

@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("小羽");
  people.setpTel("1234566");
  
  idCard.setPeople(people);
  
  entityManager.persist(idCard);
   
  JPAUtils.close();
 }
 

One-to-many problem

Demand: the correspondence between departments and employees

  • Department----->Employee

  • One-to-many relationship

Code demo:

声明部门对象

@Entity
@Table
public class Dept {
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int dId;
 
 private String dName;
 
 private String dDes;
 
 //一个部门有多个员工
 @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="dept")
 private Set<Employee> emps;
}

 

声明员工对象

@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;
}

测试

@Test
 public void testOne2Many() throws Exception {
  EntityManager entityManager=JPAUtils.getEntityManager();
  Employee emp=new Employee();
  emp.setEmpName("小娜");
  
  
  Dept dept=new Dept();
  dept.setdName("研发部");
  dept.setdDes("专门搞开发的");
  
  emp.setDept(dept);
  entityManager.persist(emp);
  
  JPAUtils.close();
 }

Many-to-many problem

Requirements: One student can be taught by multiple teachers, and one teacher can also teach multiple students

  • Student----->Teacher One-to-many

  • Teacher----->Student One-to-many

  • The ultimate relationship between teacher and student Many-to-many relationship

Code demo:

编写老师实体

@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"),          //映射的是当前这个类的主键
 inverseJoinColumns={@JoinColumn(name="stuNum")})     //映射的是对方表的主键
 private Set<Student> students;
}

编写学生实体

@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<Teacher> teachers;
}

测试

@Test
 public void testMany2Many() throws Exception {
   
  EntityManager em=JPAUtils.getEntityManager();
  
  Teacher teacher=new Teacher();
  teacher.settName("小羽");
  teacher.settNum("007");
  
  Set<Student> students=new HashSet<Student>();
  
  Student student=new Student();
  student.setAge(18);
  student.setStuName("小白");
  student.setStuNum(100);
  
  Student student1=new Student();
  student1.setAge(19);
  student1.setStuName("小娜");
  student1.setStuNum(1000);
  
  Student student2=new Student();
  student2.setAge(20);
  student2.setStuName("小黑");
  student2.setStuNum(10000);
  
  
  students.add(student);
  students.add(student1);
  students.add(student2);
  
  teacher.setStudents(students);
  
  em.persist(teacher);
  
  
  JPAUtils.close();
 }

Common methods in JPA

Code demo:

常见方法

public void testMethod() throws Exception {
  EntityManager entityManager=JPAUtils.getEntityManager();
  User user= new User();
  user.setUserName("小灰");
  user.setuId(1);
  
  //添加数据的方法
//  entityManager.persist(user);
  
  //查询数据
  //User user2=entityManager.find(User.class,1);
  
  //这个写的是HQL语句
//  Query query=entityManager.createQuery("from User");
//  List list=query.getResultList();
  
  //下面这个方法有主键值 那么就修改  没有主键值 就插入
  //entityManager.merge(user);
  
  /*创建的是本地SQL的查询
  Query query=entityManager.createNativeQuery("select * from user");
  List list=query.getResultList();*/
  
  //一般用在查询中 获取最新的这个数据
//  entityManager.refresh(user);
  
  User user2=entityManager.find(User.class,1);
  
  entityManager.remove(user2);
  //System.out.println(list);
  
  JPAUtils.close();
 }
 

The state of objects in JPA

Object status:

  • 新建状态: User user = new User(); has nothing to do with the database and memory, the object is just the state after it is new

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

  • 游离状态: After the current object calls the clear method and before the close method, the object is in a free state. clear : It means to clear the corresponding relationship between memory and database data

  • 删除状态: The state of the object after the current object close is called the deleted state

 

Precautions

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

Do not write column , the column name of the table is the attribute name of the class

The value after @GeneratedValue is not written and the default is auto

Conclusion

JPA is a frequently used technology that is inseparable from our development. The technology and knowledge involved are actually far more than those listed above.

Asaba will continue to update his knowledge about JPA development in the future, I only hope to be helpful to everyone, thank you for your support!

Writing upholds the original intention and is committed to making every Internet person make progress together.

Good articles in the past

Recommended in the past

Dynamic Resource Technology JSP|A beautiful encounter between Java and Html

Detailed explanation of the most aunt-level Java inheritance in the history of "4D graphics"

Still able to eat | technology is getting newer and newer, I still love my old friend jQuery as always

Farewell to Prayer Programming|The correct landing posture of unit testing in the project

Small note | One week online million-level high concurrency system

Components must know and know | Wheels we used in those years-Filter and Proxy

[CV plus points] Hexo framework builds personal blog site, hands-on teaching.

ES Development Guide|How to quickly get started with ElasticSearch

‍‍‍

If you think Qianyu's article is helpful to you, please search on WeChat and follow the WeChat official account of "Qianyu's IT House" . I will share computer information knowledge, theoretical technology, tool resources, software introduction, and back-end development here. , Interviews, feelings about work, and some life thoughts and other series of articles. What you see is life. Take your time, work harder, you and I grow together...

Just a little bit, one-click three consecutive is here!

 

Guess you like

Origin blog.csdn.net/weixin_43719843/article/details/109913377