Hibernate&JPA快速搭建

2023-12-14 10:37:02

1. 先创建一个普通Maven工程,导入依赖

  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.32.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>

2.创建实体类

package com.kuang.pojo;

import javax.persistence.*;

@Entity//作为 hibernate实体类
@Table(name = "tb_customer")//映射的表名
public class Customer {

    /**
     * @Id: 声明主键的配置
     * @GeneratedValue: 配置主键的生成策略
     *        strategy :
     *            1. GenerationType.IDENTITY :自增 mysql
     *               底层数据库必须支持自动增长 (底层数据库支持的自动增长方式,对id自增)
     *            2. GenerationType.SEQUENCE : 序列 ,oracle
     *               底层书库必须支持序列
     *            3. GenerationType.TABLE : jpa 提供的一种机制, 通过一张数据库表的形式帮助我们完成主键的配置
     *            4. GenerationType.AUTO : 由程序自动的帮助我们选择主键生成策略
     *   @Column(name = "cust_id") 配置属性和字段的映射关系
     *       name: 数据库表中字段的名称
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;//客户的主键

    @Column(name = "cust_name")
    private String custName;//客户的名称

    @Column(name = "cust_address")
    private String custAddress;

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custAddress='" + custAddress + '\'' +
                '}';
    }
}

3.?在 resource 文件夹下创建 hibernate.cfg.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>
        <!--数据源配置,数据库账号密码配自己的-->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/springdata_jpa?useUnicode=true&amp;useSSL=false&amp;characterEncoding=UTF-8</property>
        <property name="connection.username">root</property>
        <property name="connection.password">2001</property>


        <!--        设置数据库方言,现在我们用的是mysql所以设置mysql的方言,这样 hibernate 可以根据 mysql 的语法去生成执行语句-->
        <property name="dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

        <!--        打印SQL语句,方便排查 默认为false-->
        <property name="show_sql">true</property>
        <!--        格式化SQL语句,方便排查 默认为false-->
        <property name="format_sql">true</property>
        <!--        是否自动生成数据表
                     默认为none 不自动生成
                     update  如果没有表会创建,有会检查更新
                     create  创建
                                           -->
        <property name="hbm2ddl.auto">update</property>

        <!--        注册实体关系映射文件  指定哪些pojo 需要进行ORM映射-->
        <mapping class="com.kuang.pojo.Customer"></mapping>

<!--        <mapping resource="com/kuang/pojo/Customer.hbm.xml"></mapping>-->
    </session-factory>

</hibernate-configuration>

如果你要找其他的数据库方言? 两下Shift

进入这个类 按 ctrl +H

?4.创建测试类 测试增删改查操作

package com.kuang.test;

import com.kuang.pojo.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class Hibernate {

    // 当中 sqlSessionFactory     session: 数据库会话  代码和数据库的一个桥梁
    private SessionFactory sf;

    @Before
    public void init(){
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("/hibernate.cfg.xml").build();
        //2.根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的session工厂
        sf=new MetadataSources(registry).buildMetadata().buildSessionFactory();

    }

    @Test
    public void testInsert(){

        //session 进行持久化操作
        Session session = null;
        Transaction transaction =null;
        try{
           session = sf.openSession();
          transaction = session.beginTransaction();
            Customer customer = new Customer();
            customer.setCustName("李六");
            customer.setCustAddress("武汉");
            session.save(customer);

            transaction.commit();

        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (session!=null){
                session.close();
            }
        }
    }

    @Test
    public void testSelect(){

        //session 进行持久化操作
        Session session = null;
        Transaction transaction =null;
        try{
            session = sf.openSession();
            transaction = session.beginTransaction();

            Customer customer = session.find(Customer.class, 2L);
//            Customer customer = session.load(Customer.class, 1L);//懒加载,什么时候用到customer这个对象才会去查询
            System.out.println(customer);

            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (session!=null){
                session.close();
            }
        }


    }

    @Test
    public void testUpdate(){

        //session 进行持久化操作
        Session session = null;
        Transaction transaction =null;
        try{
            session = sf.openSession();
            transaction = session.beginTransaction();

            Customer customer = new Customer();
            customer.setCustId(2L);
            customer.setCustName("大象");
            customer.setCustAddress("苏州");
        //这是个覆盖操作
            session.saveOrUpdate(customer);


            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (session!=null){
                session.close();
            }
        }


    }

    @Test
    public void testRemove(){

        //session 进行持久化操作
        Session session = null;
        Transaction transaction =null;
        try{
            session = sf.openSession();
            transaction = session.beginTransaction();

            Customer customer = new Customer();
            customer.setCustId(2L);

            //这是个覆盖操作
            session.remove(customer);


            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (session!=null){
                session.close();
            }
        }


    }


    @Test
    public void testHQL(){

        //session 进行持久化操作
        Session session = null;
        Transaction transaction =null;
        try{
            session = sf.openSession();
            transaction = session.beginTransaction();


            // 可以 :columnName 占位符  已经不支持 ? 占位符了
            String hql=" FROM Customer where custId=:custid";

            List<Customer> resultList = session.createQuery(hql, Customer.class).setParameter("custid",3L).getResultList();
            System.out.println(resultList);

            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (session!=null){
                session.close();
            }
        }


    }

    @Test
    public void template(){

        //session 进行持久化操作
        Session session = null;
        Transaction transaction =null;
        try{
            session = sf.openSession();
            transaction = session.beginTransaction();








            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (session!=null){
                session.close();
            }
        }


    }
}

文章来源:https://blog.csdn.net/qq_53374893/article/details/134905023
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。