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;

结构如下

hibernate+JPA实现对数据库的增删改查_第1张图片

1.2在idea中新建mysql连接

用于反射生成实体类

hibernate+JPA实现对数据库的增删改查_第2张图片

2.idea新建maven项目

2.1新建maven项目

hibernate+JPA实现对数据库的增删改查_第3张图片

2.2调整项目结构

2.2.1 新增源码目录

项目新建完毕后在main下创建一个java目录存放源码,并标记为source root
hibernate+JPA实现对数据库的增删改查_第4张图片
在java 下新建4个包备用
com.yang.entity
com.yang.dao
com.yang.test
com.yang.util
hibernate+JPA实现对数据库的增删改查_第5张图片

2.2.2添加依赖

hibernate与mysql驱动依赖

    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-coreartifactId>
      <version>5.2.9.Finalversion>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.39version>
    dependency>

2.2.3 把项目设置成JPA工程

1.打开项目结构设置

hibernate+JPA实现对数据库的增删改查_第6张图片

2.设置JPA工程

hibernate+JPA实现对数据库的增删改查_第7张图片

3.新增persistence.xml

hibernate+JPA实现对数据库的增删改查_第8张图片

需要强调的是persistence.xml必须位于如下目录:
src\main\resources\META-INF\persistence.xml
因为在Java™SE环境中,Hibernate需要通过META-INF/persistence.xml资源名称的类路径查找来定位所有JPA配置文件。

hibernate+JPA实现对数据库的增删改查_第9张图片

3.生成实体类

hibernate+JPA实现对数据库的增删改查_第10张图片

hibernate+JPA实现对数据库的增删改查_第11张图片

生成studentEntity

4配置persistence.xml


<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="YANG">
        <class>com.yang.entity.StudentEntityclass>
        <properties>
            
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            
            <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"/>
            
            <property name="hibernate.format_sql" value="true"/>
            
            <property name="hibernate.use_sql_comments" value="false"/>
            
            <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 findAll() {
        EntityManager entityManager = HibernateSessionFactory.getEntityManager();
        entityManager.getTransaction().begin();
        List 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.增删改查的详细操作

见hibernate官网
http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html

7项目github地址

https://github.com/matrix-yang/jpamodel

你可能感兴趣的:(基础入门)