1. 程式人生 > >hibernate+JPA實現對資料庫的增刪改查

hibernate+JPA實現對資料庫的增刪改查

環境準備

  • mysql+navicat for mysql
  • jdk1.8
  • maven
  • interij idea

1.新建資料庫

1.1建庫

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `sex` int(11) DEFAULT NULL,
  `teacher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2
DEFAULT CHARSET=utf8;

結構如下

這裡寫圖片描述

1.2在idea中新建mysql連線

用於反射生成實體類

這裡寫圖片描述

2.idea新建maven專案

2.1新建maven專案

這裡寫圖片描述

2.2調整專案結構

2.2.1 新增原始碼目錄

專案新建完畢後在main下建立一個java目錄存放原始碼,並標記為source root
這裡寫圖片描述
在java 下新建4個包備用
com.yang.entity
com.yang.dao
com.yang.test
com.yang.util
這裡寫圖片描述

2.2.2新增依賴

hibernate與mysql驅動依賴

    <dependency
>
<groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.9.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId
>
<version>5.1.39</version> </dependency>

2.2.3 把專案設定成JPA工程

1.開啟專案結構設定

這裡寫圖片描述

2.設定JPA工程

這裡寫圖片描述

3.新增persistence.xml

這裡寫圖片描述

需要強調的是persistence.xml必須位於如下目錄:
src\main\resources\META-INF\persistence.xml
因為在Java™SE環境中,Hibernate需要通過META-INF/persistence.xml資源名稱的類路徑查詢來定位所有JPA配置檔案。

這裡寫圖片描述

3.生成實體類

這裡寫圖片描述

這裡寫圖片描述

生成studentEntity

4配置persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="YANG">
        <class>com.yang.entity.StudentEntity</class>
        <properties>
            <!--宣告資料庫連線的驅動-->
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <!--jdbc資料庫的連線地址-->
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate_jpa"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <!--配置方言-->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <!--啟用查詢日誌功能-->
            <property name="hibernate.show_sql" value="true"/>
            <!--優雅地輸出Sql-->
            <property name="hibernate.format_sql" value="true"/>
            <!--新增一條解釋型標註-->
            <property name="hibernate.use_sql_comments" value="false"/>
            <!--配置如何根據java模型生成資料庫表結構,常用update,validate-->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

5.編寫測試類

5.1在com.yang.util下新建:

package com.yang.util;

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

public class HibernateSessionFactory {
    @PersistenceUnit
    private static final EntityManagerFactory entityManagerFactory;
    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("YANG");
    }

    public static EntityManager getEntityManager(){
        return entityManagerFactory.createEntityManager();
    }
}

5.2在com.yang.dao下新建

package com.yang.dao;

import com.yang.entity.StudentEntity;
import com.yang.util.HibernateSessionFactory;

import javax.persistence.EntityManager;
import java.util.List;

public class StudentDAO {
    public void save(StudentEntity studentEntity) {
        EntityManager entityManager = HibernateSessionFactory.getEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(studentEntity);
        entityManager.getTransaction().commit();
        entityManager.close();
    }

    public List<StudentEntity> findAll() {
        EntityManager entityManager = HibernateSessionFactory.getEntityManager();
        entityManager.getTransaction().begin();
        List<StudentEntity> result = entityManager.createQuery("select p " +
                "from StudentEntity p ").getResultList();
        entityManager.getTransaction().commit();
        entityManager.close();
        return result;
    }

}

5.3在com.yang.test下新建

package com.yang.test;


import com.yang.entity.StudentEntity;
import com.yang.dao.StudentDAO;

public class StartMain {
    public static void  main(String[] args){
        StudentEntity studentEntity=new StudentEntity();
        studentEntity.setName("yang");
        StudentDAO studentDAO=new StudentDAO();
        studentDAO.save(studentEntity);
    }
}

5.4 調整生成的entity
hibernate5.2 用@table有可能會丟擲異常需要修改

package com.yang.entity;

import javax.persistence.*;

@Entity(name = "student")
public class StudentEntity {
    private int id;
    private String name;
    private Integer sex;
    private String teacher;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

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

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "sex")
    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    @Basic
    @Column(name = "teacher")
    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        StudentEntity that = (StudentEntity) o;

        if (id != that.id) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (sex != null ? !sex.equals(that.sex) : that.sex != null) return false;
        if (teacher != null ? !teacher.equals(that.teacher) : that.teacher != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (sex != null ? sex.hashCode() : 0);
        result = 31 * result + (teacher != null ? teacher.hashCode() : 0);
        return result;
    }
}

6.增刪改查的詳細操作

7專案github地址