hibernate+JPA实现对数据库的增删改查

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_21768483/article/details/78293396

环境准备

  • 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.增删改查的详细操作

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

7项目github地址

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

展开阅读全文

没有更多推荐了,返回首页