The study notes JPA database connection

The concept: JPA is referred to as the Java Persistence API, the Chinese name of the Java Persistence API, is JDK 5.0 annotations or XML description of the object - mapping between relational tables, and run the entity object persistence to the database.

The difference between JPA and Spring-data-jpa: the reprint https://my.oschina.net/u/3080373/blog/1828589

JPA provides us with:

1) ORM mapping metadata: JPA support in the form of two kinds of annotations and XML metadata, the metadata describes the mapping relationships between the objects and the table, the frame whereby the entity object persisted to the database tables;

Such as: @ Entity, @ Table, @ Column, @ Transient annotation and so on.

 2) JPA's API: used to manipulate physical objects, perform CRUD operations, the framework for us to do everything in the background, freed developers from the tedious JDBC and SQL code.

Such as: entityManager.merge (T t);

 3) JPQL query language: Object-oriented rather than oriented database query language query the data, avoiding tight coupling of SQL statements program.

如:from Student s where s.name = ?

but:

JPA is only a norm, that is to say JPA only defines the interface, and the interface is required to achieve the work. So the underlying need some sort of realization, and Hibernate ORM framework is to achieve a JPA interfaces.

In other words:

JPA is a set of specifications ORM, Hibernate implements JPA specification! Figure:

 

What is the spring data jpa?

spirng data jpa JPA is a simplified development framework provided by spring, by convention good naming convention [Method] Write dao layer interface, can be written without the interface, to access and operation of the database. At the same time offers a lot of features such as paging, sorting, complex queries in addition to the CRUD and so on.

Spring Data JPA JPA specification may be understood as an abstract resealed, the bottom or the use of Hibernate JPA technology. Figure:

Interface naming convention:

Example:

springboot integrated spring data jpa just two steps:

The first step: Import coordinate maven

Step Two: yml profile configuration information jpa

 Self: JPA is a specification that different implementations. hibernate is one implementation, is spring-data-jpa one implementation, however, be higher degree of encapsulation of the spring-data-jpa. Benpian exercise is to learn JPA hibernate implementation and use, you can start doing demo test.

Project structure:

pojo layer: User

package com.cy.pojo;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = User.TABLE)
public class User {
    public static final String TABLE = "SYS_USERS";
    @Id
    @GenericGenerator(name = "idGenerator", strategy = "native")
    @GeneratedValue(generator = "idGenerator")
    @Column
    private Integer id;
    @Column
    private String username;
    @Column
    private String password;
    @Column
    private String salt;
    @Column
    private String email;
    @Column
    private String mobile;
    @Column
    private Integer valid;
    @Column
    private Integer deptId;
    @Column
    private Date createdTime;
    @Column
    private Date modifiedTime;
    @Column
    private String createdUser;
    @Column
    private String modifiedUser;

    public User() {
    }

    public User(Integer id, String username, String password, String salt, String email, String mobile, Integer valid, Integer deptId, Date createdTime, Date modifiedTime, String createdUser, String modifiedUser) {
        this.username = username;
        this.password = password;
        this.salt = salt;
        this.email = email;
        this.mobile = mobile;
        this.valid = valid;
        this.deptId = deptId;
        this.createdTime = createdTime;
        this.modifiedTime = modifiedTime;
        this.createdUser = createdUser;
        this.modifiedUser = modifiedUser;
    }

    public static String getTABLE() {
        return TABLE;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getValid() {
        return valid;
    }

    public void setValid(Integer valid) {
        this.valid = valid;
    }

    public Integer getDeptId() {
        return deptId;
    }

    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    public Date getModifiedTime() {
        return modifiedTime;
    }

    public void setModifiedTime(Date modifiedTime) {
        this.modifiedTime = modifiedTime;
    }

    public String getCreatedUser() {
        return createdUser;
    }

    public void setCreatedUser(String createdUser) {
        this.createdUser = createdUser;
    }

    public String getModifiedUser() {
        return modifiedUser;
    }

    public void setModifiedUser(String modifiedUser) {
        this.modifiedUser = modifiedUser;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", salt='" + salt + '\'' +
                ", email='" + email + '\'' +
                ", mobile='" + mobile + '\'' +
                ", valid=" + valid +
                ", deptId=" + deptId +
                ", createdTime=" + createdTime +
                ", modifiedTime=" + modifiedTime +
                ", createdUser='" + createdUser + '\'' +
                ", modifiedUser='" + modifiedUser + '\'' +
                '}';
    }
}

 Profile: persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
             version="2.0">
    <!--在根标签下至少要存在一个持久化单元 (有一个数据库的连接信息)-->
    <persistence-unit name="myJpa">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <!-- 配置多条数据库的信息 -->
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql:///jtsys"></property>
            <property name="hibernate.connection.username" value="root"></property>
            <property name="hibernate.connection.password" value="123456"></property>
            <!-- 方言 -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
            <property name="hibernate.show_sql" value="true"></property>
            <property name="hibernate.format_sql" value="true"></property>
            <property name="hibernate.hbm2ddl.auto" value="update"></property>
        </properties>
    </persistence-unit>
</persistence>

Test implementation:

package com.cy.connDB;

import com.cy.pojo.User;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.Date;

public class JpaConn {

    private static EntityManagerFactory entityManagerFactory;

    public static void main(String[] args) {
        /**
         * JPA连接数据库,注意问题persistence.xml的配置文件必须放在META-INF文件夹下:
         * 1.Persistence创建entityFactory对象
         * 2.通过entityManagerFactory对象创建entityManager对象
         * 3.entityManager获取事务对象
         * 4.开启事务
         * 5.操作数据库
         * 6.关闭资源
         */

        entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");
        JpaConn jpaConn = new JpaConn();
        jpaConn.saveUser();
        jpaConn.findUserById();
        jpaConn.updateUserByUsername();
        jpaConn.deleteUserById();

    }

    private void deleteUserById() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction tx = entityManager.getTransaction();
        tx.begin();
        User user = entityManager.find(User.class, 18);
        entityManager.remove(user);
        tx.commit();
        entityManager.close();
    }

    private void updateUserByUsername() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction tx = entityManager.getTransaction();
        tx.begin();
        User user = entityManager.find(User.class, 12);
        user.setUsername("zhouyu");
        entityManager.merge(user);
        tx.commit();
        entityManager.close();
    }

    private void findUserById() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        User user = entityManager.find(User.class, 12);
        System.out.println(user);
    }

    private void saveUser() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        User user = new User();
        user.setUsername("xiaoqiao");
        user.setEmail("[email protected]");
        user.setMobile("18755556666");
        user.setCreatedTime(new Date());
        user.setModifiedTime(new Date());
        user.setCreatedUser("admin");
        user.setModifiedUser("admin");
        entityManager.persist(user);
        transaction.commit();
        entityManager.close();
    }
}

 Summary: The need to pay special attention when using JPA, location persistence.xml configuration file must be placed in src / META-INF below can! ! !

JPA database connection using the steps of:

1. Read the configuration file by Persistence, create objects entityManagerFactory

2. Create entityManager objects through the object entityManagerFactory

3.entityManager acquisition transaction object

4. Turn Affairs

5. Database operations using entityManeger

6. Close the resource

Method entityManager common database operations:
void persist (Object var1); save the object
<T> T merge (T var1); Entity instance Detached state will go Managed status;
void remove (Object var1); deleted data
<T> T find (Class <T> var1, Object var2); query based on the main key
Query createQuery(CriteriaUpdate var1);
eg: Use Cases
EntityManager em = …;

CriteriaBuilder cb = em.getCriteriaBuilder();

CriteriaQuery<Entity class> cq = cb.createQuery(Entity.class);

Root<Entity> from = cq.from(Entity.class);

cq.select(Entity);
//必须要有CriteriaQuery对象,才能用此方法
TypedQuery<Entity> q = em.createQuery(cq);

List<Entity> allitems = q.getResultList();
Query createNamedQuery (String var1); through sql statement to query the database
CriteriaBuilder getCriteriaBuilder (); create criteria to query the database

 

 

Published 15 original articles · won praise 0 · Views 275

Guess you like

Origin blog.csdn.net/weixin_45146962/article/details/105007716