• SpringData Hibernate JPA 使用案例 案例 (一)


    目录

    一、Hibernate的基本操作

    1、添加依赖

    2、添加建表实体类

    3、添加hibernate配置依赖

    4、测试类

     二、SpringData实现JPA的功能

    1、添加persistence.xml配置文件

     2、JPA测试

    3、切换持久化单元的演示

     4、*HibernateJPI常见操作,测试案例*


    一、Hibernate的基本操作

    1、添加依赖

    1. <parent>
    2. <groupId>org.springframework.bootgroupId>
    3. <version>2.3.2.RELEASEversion>
    4. <artifactId>spring-boot-starter-parentartifactId>
    5. <relativePath/>
    6. parent>
    7. <properties>
    8. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    9. <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
    10. <java.version>1.8java.version>
    11. <junit.version>4.13junit.version>
    12. <hibernate.version>5.4.32.Finalhibernate.version>
    13. <mysql.version>5.1.22mysql.version>
    14. properties>
    15. <dependencies>
    16. <dependency>
    17. <groupId>org.hibernategroupId>
    18. <artifactId>hibernate-entitymanagerartifactId>
    19. <version>${hibernate.version}version>
    20. dependency>
    21. <dependency>
    22. <groupId>mysqlgroupId>
    23. <artifactId>mysql-connector-javaartifactId>
    24. <version>${mysql.version}version>
    25. dependency>
    26. <dependency>
    27. <groupId>junitgroupId>
    28. <artifactId>junitartifactId>
    29. <version>${junit.version}version>
    30. <scope>testscope>
    31. dependency>
    32. dependencies>

    2、添加建表实体类

    hibernate可以通过实体类自动生成对应的表

    1. package com.dragonwu.entity;
    2. import javax.persistence.Column;
    3. import javax.persistence.Entity;
    4. import javax.persistence.GeneratedValue;
    5. import javax.persistence.GenerationType;
    6. import javax.persistence.Id;
    7. import javax.persistence.Table;
    8. /**
    9. * @author DragonWu
    10. * @date 2022-09-20 11:17
    11. **/
    12. @Entity //作为hibernate的实体类
    13. @Table(name="tb_customer")//映射的表名
    14. public class Customer {
    15. /**
    16. * @Id 主键声明
    17. * @GeneratedValue: 配置主键的生成策略
    18. * strategy
    19. * GenerationType.IDENTITY: 自增,mysql
    20. * *底层数据库必须支持自动增长
    21. * GenerationType.SEQUENCE: 序列oracle
    22. * *底层数据库必须支持序列
    23. * GenerationType.TABLE: jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键
    24. * GenerationType.AUTO: 由程序自动地帮助我们选择主键生成策略
    25. * @Cloumn 配置属性和表字段的映射关系
    26. * name: 数据库表中字段的名称
    27. */
    28. @Id
    29. @GeneratedValue(strategy = GenerationType.IDENTITY)
    30. @Column(name="id",length = 20)
    31. private Long id;
    32. @Column(name="cus_name",columnDefinition = "varchar(32) default null comment '客户名'")
    33. private String name;//客户名
    34. @Column(name="cus_address",length = 200)
    35. private String address;//客户地址
    36. public Long getId() {
    37. return id;
    38. }
    39. public void setId(Long id) {
    40. this.id = id;
    41. }
    42. public String getName() {
    43. return name;
    44. }
    45. public void setName(String name) {
    46. this.name = name;
    47. }
    48. public String getAddress() {
    49. return address;
    50. }
    51. public void setAddress(String address) {
    52. this.address = address;
    53. }
    54. @Override
    55. public String toString() {
    56. return "Customer{" +
    57. "id=" + id +
    58. ", name='" + name + '\'' +
    59. ", address='" + address + '\'' +
    60. '}';
    61. }
    62. }

    3、添加hibernate配置依赖

    这里建议命名为hibernate.cfg.xml,我存放的目录在resource/hibernate/hibernate.cfg.xml

    1. hibernate-configuration PUBLIC
    2. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    3. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    4. <hibernate-configuration>
    5. <session-factory>
    6. <property name="connection.url">jdbc:mysql://my-server:3306/testproperty>
    7. <property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
    8. <property name="hibernate.connection.username">rootproperty>
    9. <property name="hibernate.connection.password">XXXproperty>
    10. <property name="connection.characterEncoding">utf8property>
    11. <property name="hibernate.dialect">org.hibernate.dialect.MySQL57Dialectproperty>
    12. <property name="show_sql">trueproperty>
    13. <property name="format_sql">trueproperty>
    14. <property name="hbm2ddl.auto">updateproperty>
    15. <mapping class="com.dragonwu.entity.Customer"/>
    16. session-factory>
    17. hibernate-configuration>

    4、测试类

    1. package com.dragonwu.test;
    2. import com.dragonwu.entity.Customer;
    3. import org.hibernate.Session;
    4. import org.hibernate.SessionFactory;
    5. import org.hibernate.Transaction;
    6. import org.hibernate.boot.MetadataSources;
    7. import org.hibernate.boot.registry.StandardServiceRegistry;
    8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    9. import org.junit.Before;
    10. import org.junit.Test;
    11. import java.util.List;
    12. /**
    13. * @author DragonWu
    14. * @date 2022-09-20 12:52
    15. **/
    16. public class HibernateTest {
    17. //Session工厂 Session:数据库会话 代码持久化操作数据库的一个桥梁
    18. private SessionFactory sf;
    19. @Before
    20. public void init() {
    21. StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("/hibernate/hibernate.cfg.xml").build();
    22. //2、根据服务注册类持久一个元数据资源集,同时构建元数据并生成应用一般唯一的session工厂
    23. sf = new MetadataSources(registry).buildMetadata().buildSessionFactory();
    24. }
    25. @Test
    26. public void testC() {
    27. //session进行持久化操作
    28. try (Session session = sf.openSession()) {
    29. Transaction tx = session.beginTransaction();
    30. Customer customer = new Customer();
    31. customer.setName("DragonWu");
    32. session.save(customer);
    33. tx.commit();
    34. }
    35. }
    36. @Test
    37. public void testR() {
    38. //session进行持久化操作
    39. try (Session session = sf.openSession()) {
    40. Transaction tx = session.beginTransaction();
    41. Customer customer = session.find(Customer.class, 1L);
    42. System.out.println("===================");
    43. System.out.println(customer);
    44. tx.commit();
    45. }
    46. }
    47. @Test
    48. public void testR_lazy() {
    49. //session进行持久化操作
    50. try (Session session = sf.openSession()) {
    51. Transaction tx = session.beginTransaction();
    52. Customer customer = session.load(Customer.class, 1L);
    53. System.out.println("===================");
    54. System.out.println(customer);
    55. tx.commit();
    56. }
    57. }
    58. @Test
    59. public void testU() {
    60. //session进行持久化操作
    61. try (Session session = sf.openSession()) {
    62. Transaction tx = session.beginTransaction();
    63. Customer customer = new Customer();
    64. customer.setId(1L);
    65. customer.setAddress("杭州");
    66. //session.save()插入
    67. //session.update()更新
    68. session.saveOrUpdate(customer);//存在id时更新,不存在id时创建
    69. tx.commit();
    70. }
    71. }
    72. @Test
    73. public void testD() {
    74. //session进行持久化操作
    75. try (Session session = sf.openSession()) {
    76. Transaction tx = session.beginTransaction();
    77. Customer customer = new Customer();
    78. customer.setId(1L);
    79. session.remove(customer);
    80. tx.commit();
    81. }
    82. }
    83. @Test
    84. public void testR_HQL() {
    85. //session进行持久化操作
    86. try (Session session = sf.openSession()) {
    87. Transaction tx = session.beginTransaction();
    88. String hql = " FROM Customer where id=:id";
    89. List resultList = session
    90. .createQuery(hql, Customer.class)
    91. .setParameter("id",2L)
    92. .getResultList();
    93. System.out.println(resultList);
    94. tx.commit();
    95. }
    96. }
    97. }

    在对应连接里创建对应数据库,运行单元测试类testC

    表已自动生成。 

    单元测试testR

     单元测试testR_lazy懒加载,load懒加载当执行到对应查询时系统才会执行查询,而find会先执行查询。

     二、SpringData实现JPA的功能

    用之前的hibernate,如果我们需要修改持久化层,需要修改很多配置以及代码,由此SpringData推出了JPA的功能。JPA同样是钟规范,需要依赖于他的实现。

    1、添加persistence.xml配置文件

    目录结构如图:

    1. "1.0" encoding="UTF-8"?>
    2. <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    3. <persistence-unit name="hibernateJPA" transaction-type="RESOURCE_LOCAL">
    4. <provider>org.hibernate.jpa.HibernatePersistenceProviderprovider>
    5. <class>com.dragonwu.entity.Customerclass>
    6. <properties>
    7. <property name="javax.persistence.jdbc.user" value="root"/>
    8. <property name="javax.persistence.jdbc.password" value="XXX"/>
    9. <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    10. <property name="javax.persistence.jdbc.url" value="jdbc:mysql://my-server:3306/test?characterEncoding=UTF-8"/>
    11. <property name="hibernate.show_sql" value="true"/>
    12. <property name="hibernate.format_sql" value="true"/>
    13. <property name="hibernate.hbm2ddl.auto" value="update"/>
    14. properties>
    15. persistence-unit>
    16. persistence>

     2、JPA测试

    1. package com.dragonwu.test;
    2. import com.dragonwu.entity.Customer;
    3. import org.junit.Before;
    4. import org.junit.Test;
    5. import javax.persistence.EntityManager;
    6. import javax.persistence.EntityManagerFactory;
    7. import javax.persistence.EntityTransaction;
    8. import javax.persistence.Persistence;
    9. /**
    10. * @author DragonWu
    11. * @date 2022-09-20 15:13
    12. **/
    13. public class JPATest {
    14. EntityManagerFactory factory;
    15. @Before
    16. public void before(){
    17. factory= Persistence
    18. .createEntityManagerFactory("hibernateJPA");
    19. }
    20. @Test
    21. public void testC(){
    22. EntityManager em=factory.createEntityManager();
    23. EntityTransaction tx=em.getTransaction();
    24. tx.begin();
    25. Customer customer = new Customer();
    26. customer.setName("龘龘");
    27. em.persist(customer);
    28. tx.commit();
    29. }
    30. }

    3、切换持久化单元的演示

    添加另一种jpa的依赖

    1. <dependency>
    2. <groupId>org.apache.openjpagroupId>
    3. <artifactId>openjpa-allartifactId>
    4. <version>3.2.0version>
    5. dependency>

    添加openjpa单元项后的persistence.xml文件

    1. "1.0" encoding="UTF-8"?>
    2. <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    3. <persistence-unit name="hibernateJPA" transaction-type="RESOURCE_LOCAL">
    4. <provider>org.hibernate.jpa.HibernatePersistenceProviderprovider>
    5. <class>com.dragonwu.entity.Customerclass>
    6. <properties>
    7. <property name="javax.persistence.jdbc.user" value="root"/>
    8. <property name="javax.persistence.jdbc.password" value="XXX"/>
    9. <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    10. <property name="javax.persistence.jdbc.url" value="jdbc:mysql://my-server:3306/test?characterEncoding=UTF-8"/>
    11. <property name="hibernate.show_sql" value="true"/>
    12. <property name="hibernate.format_sql" value="true"/>
    13. <property name="hibernate.hbm2ddl.auto" value="update"/>
    14. properties>
    15. persistence-unit>
    16. <persistence-unit name="openJPA" transaction-type="RESOURCE_LOCAL">
    17. <provider>org.apache.openjpa.persistence.PersistenceProviderImplprovider>
    18. <class>com.dragonwu.entity.Customerclass>
    19. <properties>
    20. <property name="javax.persistence.jdbc.user" value="root"/>
    21. <property name="javax.persistence.jdbc.password" value="XXX"/>
    22. <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    23. <property name="javax.persistence.jdbc.url" value="jdbc:mysql://my-server:3306/test?characterEncoding=UTF-8"/>
    24. <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
    25. properties>
    26. persistence-unit>
    27. persistence>

    使用openJPA我们只需要改变单元项即可,代码耦合性很低,非常适合装配使用。

    1. package com.dragonwu.test;
    2. import com.dragonwu.entity.Customer;
    3. import org.junit.Before;
    4. import org.junit.Test;
    5. import javax.persistence.EntityManager;
    6. import javax.persistence.EntityManagerFactory;
    7. import javax.persistence.EntityTransaction;
    8. import javax.persistence.Persistence;
    9. /**
    10. * @author DragonWu
    11. * @date 2022-09-20 15:13
    12. **/
    13. public class JPATest {
    14. EntityManagerFactory factory;
    15. @Before
    16. public void before(){
    17. factory= Persistence
    18. .createEntityManagerFactory("openJPA");
    19. }
    20. @Test
    21. public void testC(){
    22. EntityManager em=factory.createEntityManager();
    23. EntityTransaction tx=em.getTransaction();
    24. tx.begin();
    25. Customer customer = new Customer();
    26. customer.setName("DragonWu Master");
    27. em.persist(customer);
    28. tx.commit();
    29. }
    30. }

    查看效果:可以看到两种不同的单元项都可以对数据库进行操作,而底层都是基于hibernate来实现的。

     4、*HibernateJPI常见操作,测试案例*

    1. package com.dragonwu.test;
    2. import com.dragonwu.entity.Customer;
    3. import org.junit.Before;
    4. import org.junit.Test;
    5. import javax.persistence.EntityManager;
    6. import javax.persistence.EntityManagerFactory;
    7. import javax.persistence.EntityTransaction;
    8. import javax.persistence.Persistence;
    9. /**
    10. * @author DragonWu
    11. * @date 2022-09-20 15:13
    12. **/
    13. public class JPATest {
    14. EntityManagerFactory factory;
    15. @Before
    16. public void before(){
    17. factory= Persistence
    18. .createEntityManagerFactory("hibernateJPA");
    19. }
    20. @Test
    21. public void testC(){
    22. EntityManager em=factory.createEntityManager();
    23. EntityTransaction tx=em.getTransaction();
    24. tx.begin();
    25. Customer customer = new Customer();
    26. customer.setName("DragonWu Master");
    27. em.persist(customer);
    28. tx.commit();
    29. }
    30. @Test
    31. public void testR(){
    32. EntityManager em=factory.createEntityManager();
    33. EntityTransaction tx=em.getTransaction();
    34. tx.begin();
    35. Customer customer = em.find(Customer.class,4L);
    36. //find立即查询
    37. System.out.println("==============================");
    38. System.out.println(customer);
    39. tx.commit();
    40. }
    41. @Test
    42. public void testR_lazy(){
    43. EntityManager em=factory.createEntityManager();
    44. EntityTransaction tx=em.getTransaction();
    45. tx.begin();
    46. Customer customer = em.getReference(Customer.class,4L);
    47. //load延时查询
    48. System.out.println("==============================");
    49. System.out.println(customer);
    50. tx.commit();
    51. }
    52. @Test
    53. public void testU(){
    54. EntityManager em=factory.createEntityManager();
    55. EntityTransaction tx=em.getTransaction();
    56. tx.begin();
    57. Customer customer=new Customer();
    58. customer.setId(5L);
    59. customer.setName("Jack");
    60. //如果该id对应的数据存在则更新,否则添加;更新时会先查询是否有变化,若有变化才会更新
    61. em.merge(customer);
    62. tx.commit();
    63. }
    64. @Test
    65. public void testU_JPQL(){
    66. EntityManager em=factory.createEntityManager();
    67. EntityTransaction tx=em.getTransaction();
    68. tx.begin();
    69. //注意这里是类名
    70. String jpql="UPDATE Customer set name=:name where id=:id";
    71. em.createQuery(jpql)
    72. .setParameter("name","好人")
    73. .setParameter("id",5L)
    74. .executeUpdate();
    75. tx.commit();
    76. }
    77. @Test
    78. public void testU_SQL(){
    79. EntityManager em=factory.createEntityManager();
    80. EntityTransaction tx=em.getTransaction();
    81. tx.begin();
    82. //注意这里是表名
    83. String sql="UPDATE tb_customer set cus_name=:name where id=:id";
    84. em.createNativeQuery(sql)
    85. .setParameter("name","坏人")
    86. .setParameter("id",5L)
    87. .executeUpdate();
    88. tx.commit();
    89. }
    90. @Test
    91. public void testD(){
    92. EntityManager em=factory.createEntityManager();
    93. EntityTransaction tx=em.getTransaction();
    94. tx.begin();
    95. Customer customer=em.find(Customer.class,5L);
    96. //这里不支持删除游离态的对象
    97. em.remove(customer);
    98. tx.commit();
    99. }
    100. }
  • 相关阅读:
    Dynamsoft Barcode Reader新框架将医疗视觉提升到新水平
    《Head First HTML5 javascript》第10章 自定义对象
    大数据Flink(八十一):SQL 时区问题
    JavaScript基础知识15——专业术语:语句和表达式
    未来展望:Starday供应链火力全开,为跨境电商再添动力!
    Linux下安装Mysql【详细】
    c<8>指针
    TOREX | 单功能充电IC的外置电流通路电路
    K8S容器持续Terminating无法正常关闭(sider-car容器异常,微服务容器正常)
    自媒体短视频运营常见的5个问题及解决方案
  • 原文地址:https://blog.csdn.net/qq_50909707/article/details/126951253