发布于 2年前

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();
        }
    }
}
©2020 edoou.com   京ICP备16001874号-3