JPA Hibernate 快速入门

为了学习JPA的实体状态的转化,我们先搭建一个通过JPA Hibernate存储实体到数据库的Demo,后续的学习都在此demo基础上展开。

添加Hibernate依赖 

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-entitymanager</artifactId>
  <version>5.4.4.Final</version>
</dependency>

添加JDBC驱动

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <version>1.4.199</version>
</dependency>

META-INF/persistence.xml添加JPA和数据库配置文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="Hibernate-JPA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
            <!-- H2 is running in pure in Memory db mode, data will be lost as soon as connection is closed -->
            <property name="hibernate.connection.url" value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.pool_size" value="5"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

各位请注意:这里有一个标签<persistence-unit>

这个标签的作用我们以后结合JPA架构进行学习和理解

创建试题管理器工厂类

public class JPAUtil {

    public static EntityManagerFactory getEntityManagerFactory() {

        EntityManagerFactory entityManagerFactory = Persistence
                .createEntityManagerFactory("Hibernate-JPA");
        return entityManagerFactory;
    }
}

映射实体类

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

@Entity
@Table(name = "teachers")
public class Teacher {
    @Id
    @GeneratedValue
    private Long id;
    private String email;
    //Must have empty constructor
    public Teacher() {
    }

    public Teacher(String email) {
        this.email = email;
    }
    //Getter/setter, toString() etc

    public Long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", email='" + email + '\'' +
                '}';
    }
}

使用实体管理器类CRUD实体

import com.jpa.demo.model.Teacher;
import com.jpa.demo.utils.JPAUtil;

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

public class TeacherDao {
    private EntityManagerFactory entityManagerFactory = JPAUtil.getEntityManagerFactory();
    public Long save(Teacher teacher) {
        EntityManager entityManager = null;
        Long id = null;
        try {
            entityManager = this.entityManagerFactory.createEntityManager();
            EntityTransaction tx = entityManager.getTransaction();
            tx.begin();
            entityManager.persist(teacher);
            id = teacher.getId();
            tx.commit();
        } finally {
            entityManager.close();
        }
        return id;
    }

    public Teacher find(Long id) {
        EntityManager entityManager = null;
        Teacher teacher = null;
        try {
            entityManager = this.entityManagerFactory.createEntityManager();
            EntityTransaction tx = entityManager.getTransaction();
            tx.begin();
            teacher =  entityManager.find(Teacher.class,id);
            teacher.setEmail("updateEmail@devnote.pro");
            tx.commit();
        } finally {
            entityManager.close();
        }
        return teacher;
    }

}

测试

public class App 
{
    public static void main( String[] args )
    {
        try {
            Teacher teacher = new Teacher("email@dot.com");
            TeacherDao teacherDao = new TeacherDao();
            Long id = teacherDao.save(teacher);
            System.out.println("Student created with id: " + id);
            teacher = teacherDao.find(id);
            System.out.println("\n\n" + teacher);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

版权声明:著作权归作者所有。

相关推荐

Ubuntu 18.04快速安装gcc

默认的Ubuntu存储库包含一个名为build-essential的元包,它包含GCC编译器以及编译软件所需的许多库和其他实用程序。我们使用build-essential就可以快速安装gcc。1、更新包列表首先,我们先更新下apt的包列表:$ sudo apt update2、安装build-essential接着,我们就可以安装build-essential$ sudo apt install

winsw快速注册Windows系统服务

winsw(Windows Service Wrapper)是一个开源项目,它可以让我们快速把一个可执行的程序注册为Windows的系统服务。下载安装下载地址:https://github.com/kohsuke/winsw/releases,如图:下载对应平台的.exe(.net2和.net4)。下载地址提供了两份配置文件:sample-allOptions.xml:包含所有配置项 s

React Apollo入门

入门Apollo Client最简单的方法是使用Apollo Boost,它会给客户端配置推荐的设置。使用Apollo Boost创建app的内容包括缓存,本地状态管理以及错误处理。安装首先安装以下的软件包:npm install apollo-boost react-apollo graphql-tag graphq

IndexDB快速入门

IndexDB是适用于浏览器的文档数据库,它有以下特点:兼容所有现代的浏览器支持事务以及版本控制支持无限数量的数据。很多浏览器会限定localStorage或者sessionStorage的存储空间为2M到10MIndexDB是异步的API,它不会阻塞浏览器UI的渲染下面介绍下它的使用。安装依赖包idb需要把idb的js库添加到依赖。有几种方式添加idb到依赖。yarnyarn add&

代码编辑器monaco-editor用法入门

monaco editor是微软开源的一款web版代码编辑器。它支持智能提示,代码高亮,代码格式化。这里简单介绍下它的用法。1、下载安装monaco-editornpm install monaco-editor下载后,安装目录为node_modules/monaco-editor/。2、添加loader.js脚本到页面在集成monaco-editor的页面,添加&l

SpringBoot入门示例

创建Maven POM文件在pom.xml添加内容如下:<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht