JPA - Hibernate

本文介绍了JPA作为ORM规范的原理,详细讲解了Hibernate入门,包括POM配置、hibernate.cfg.xml设置、POJO设计及测试。还探讨了JPA在Hibernate基础上的扩展,展示了Spring整合JPA-Hibernate的XML和注解配置方式,并提供了动态查询的QueryDSL应用。最后,文章提到了SpringBoot中整合JPA的步骤和测试。
摘要由CSDN通过智能技术生成

JPA本身是一种规范,它的本质是一种ORM规范(不是ORM框架,因为JPA并未提供ORM实现,只是制定了规范)因为JPA是一种规范,所以,只是提供了一些相关的接口,但是接口并不能直接使用,JPA底层需要某种JPA实现,JPA现在就是Hibernate功能的一个子集

Hibernate入门

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lb</groupId>
    <artifactId>jpa-hibernate</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

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

        <!-- hibernate 对jpa的支持包 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.32.Final</version>
        </dependency>

        <!-- Mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!-- 单独引入lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

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>
        <!-- 启动Hibernate时,重建数据库 create;更新数据库 update , 默认不自动生成none-->
        <property name="hbm2ddl.auto">update</property>
        <!--显示执行的SQL语句-->
        <property name="show_sql">true</property>
        <!--是否格式化SQL语句-->
        <property name="format_sql">true</property>
        <!-- 数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL55Dialect</property>

        <!-- driver url username password -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/springdata_jpa?useUnicode=true&amp;characterEncoding=UTF8&amp;useSSL=false</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC连接池(使用内置的连接池)-->
        <property name="connection.pool_size">5</property>
        <!-- 每次从数据库中取出,并放到JDBC的Statment中的记录条数,fetch_size设的越大,读取数据库的次数会越小,速度越快,但消耗更多内存 -->
        <property name="jdbc.fetch_size">50</property>
        <!-- 批量插入、删除和更新时,每次操作的记录数,batch_size越大,向数据库发送SQL语句的次数越少,速度越快,但消耗更多内存 -->
        <property name="jdbc.batch_size">30</property>
        <!-- Hibernate自动管理上下文的策略 -->
        <property name="current_session_context_class">thread</property>

        <!-- 配置mapping -->
        <!-- (1)hbm.xml 映射文件配置 -->
<!--        <mapping resource="com/uzipi/entity/Customer.hbm.xml" />-->
        <!-- (2)持久化类上的注解方式 -->
        <mapping class="com.lb.pojo.Customer" />

    </session-factory>
</hibernate-configuration>

注意dialect方言的选择, 会影响是否可以成功创建表,或者表的引擎的选择。

POJO

@Data
@Entity //作为hibernate实体类
@Table(name = "tb_customer")  //映射的表名
public class Customer {
    /**
     * @Id 声明主键的配置
     * @GeneratedValue 配置主键的生成策略
     *      strategy
     *          GenerationType.IDENTITY : 自增 mysql
     *              底层数据库必须支持自动增长。对Id自增
     *          GenerationType.SEQUENCE : 序列,oracle
     *              定数据库必须支持序列
     *          GenerationType.TABLE    : JPA提供的一种机制,通过一张数据库表的形式帮助我们完成主键生成
     *          GenerationType.AUTO    : 由程序自动的帮助主键生成策略
     * @Column 配置属性和字段的映射关系
     *      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 class HibernateTest {
    private SessionFactory sessionFactory;

    @Before
    public void init() {
        StandardServiceRegistry registry =
                new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();

    }
    @Test
    public void test01(){
        try(Session session = sessionFactory.openSession()){
            Transaction tx = session.beginTransaction();

            Customer customer = new Customer();
            customer.setCustName("李四");
            session.save(customer);

            tx.commit();
        }
    }
}

注意当Customer对应的表在数据库中不存在时,会执行创建表的操作,在进行save操作

log:

Hibernate: 
    
    create table tb_customer (
       cust_id bigint not null auto_increment,
        cust_address varchar(255),
        cust_name varchar(255),
        primary key (cust_id)
    ) engine=InnoDB
Hibernate: 
    insert 
    into
        tb_customer
        (cust_address, cust_name) 
    values
        (?, ?)
public class HibernateTest {
    private SessionFactory sessionFactory;

    @Before
    public void init() {
        StandardServiceRegistry registry =
                new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();

    }

    @Test
    public void test_save() {
        try (Session session = sessionFactory.openSession()) {
            Transaction tx = session.beginTransaction();

            Customer customer = new Customer();
            customer.setCustName("李四");
            session.save(customer);

            tx.commit();
        }
    }

    @Test
    public void test_find() {
        try (Session session = sessionFactory.openSession()) {
            Transaction tx = session.beginTransaction();

            Customer customer = session.find(Customer.class, 1L);
            System.out.println(customer);
            tx.commit();
        }
    }

    @Test
    public void test_load() {
        try (Session session = sessionFactory.openSession()) {
            Transaction tx = session.beginTransaction();
            //load懒加载,使用时才会执行查询
            Customer customer = session.load(Customer.class, 1L);
            System.out.println("========================");
            System.out.println(customer);
            tx.commit();
        }
    }

    @Test
    public void test_update() {
        try (Session session = sessionFactory.openSession()) {
            Transaction tx = session.beginTransaction();

            Customer customer = new Customer();
            customer.setCustId(1L);
            customer.setCustName("李四2");
            //有id修改,没有id插入,或者直接使用update
            session.saveOrUpdate(customer);

            tx.commit();
        }
    }

    @Test
    public void tes
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值