Hibernate中使用Spring Data JPA

Posted Miss_wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate中使用Spring Data JPA相关的知识,希望对你有一定的参考价值。

1、pom.xml中引入相关依赖

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
  
    <!-- Spring data jpa依赖 -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.11.4.RELEASE</version>
    </dependency>

    <!-- hibernate依赖 -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.1.7.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.7.Final</version>
    </dependency>
    
    <!-- mysql依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.42</version>
    </dependency>
    
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

2、JPA配置MATE-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <persistence-unit name="myjpa" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.wyl.bean.User</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/test"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="root"/>
            
            <property name=" hibernate.show_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

3、创建实体对象User.class

package com.wyl.bean;

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="users")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    
    @Column
    private String userName;
    
    @Column
    private String phone;
    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 getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return super.toString();
    }
}

4、创建测试类

package com.wyl;

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

import org.junit.Test;

import com.wyl.bean.User;

public class JpaTest {

    private EntityManagerFactory factory = Persistence.createEntityManagerFactory("myjpa");    
    
    @Test
    public void testAdd(){
        EntityManager em = factory.createEntityManager();
        User user = new User();
        user.setUserName("wang");
        user.setPhone("123422222222");
        
        em.getTransaction().begin(); //事务开启
        
        try {
            em.persist(user);  //持久化数据
            em.getTransaction().commit(); //事务提交
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            em.getTransaction().rollback(); //事务回滚
        } finally {
            em.close(); //关闭em
        }
    }
    
    @Test
    public void testFind(){
        EntityManager em = factory.createEntityManager();
        User user = em.find(User.class, 1);
        System.out.println(user.getUserName());
        em.getTransaction().begin(); //事务开启
        try {
            em.merge(user);
            em.getTransaction().commit(); //事务提交
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            em.getTransaction().rollback(); //事务回滚
        } finally {
            em.close(); //关闭em
        }
    }
    
    @Test
    public void testDelete(){
        EntityManager em = factory.createEntityManager();
        
        User user = em.find(User.class, 1); //查询到实体
        
        em.getTransaction().begin(); //事务开启
        try {
            em.remove(user);  //删除实体
            em.getTransaction().commit(); //事务提交
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            em.getTransaction().rollback(); //事务回滚
        } finally {
            em.close(); //关闭em
        }
    }
}

以上是关于Hibernate中使用Spring Data JPA的主要内容,如果未能解决你的问题,请参考以下文章

Spring Data JPA 和 Hibernate

Spring Boot 未使用 Spring Data 和 Hibernate 与 sql Server 一起运行

Spring + Hibernate 审计(无 Spring Data)

Spring Data / Hibernate使用的错误列名

优化 Spring-data / Hibernate ManyToMany 插入

Spring整合Hibernate实现Spring Data JPA (简单使用)