在SpringData JPA 中實現對持久層的操作

1.導入依賴 hibernate 這個依賴自帶實現JPA接口

<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.在resources目錄下建立 META-INF文件夾 ,創建JPA? ?persistence.xml配置文件

?persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"><!--  需要配置persistence-unit 節點持久化單元:name: 持久化單元名稱  可隨時切換, 若是OpenJPA的實現方式就 換成 OpenJPA 就可以了transaction-type: 事務管理方式JTA:分布式事務管理RESOURCE_LOCAL:本地事務管理--><persistence-unit name="hibernateJPA" transaction-type="RESOURCE_LOCAL"><!--JPA 的 實現方式    順序別搞錯,要放在class上面    --><provider>org.hibernate.jpa.HibernatePersistenceProvider</provider><!--需要進行ORM 的POJO類 --><class>com.kuang.pojo.Customer</class><!-- 可選配置 :配置 JPA 實現方 的 配置信息       --><properties><!--   數據庫信息用戶名 , javax.persistence.jdbc.user密碼  , javax.persistence.jdbc.password驅動  , javax.persistence.jdbc.driver數據庫地址 , javax.persistence.jdbc.url--><property name="javax.persistence.jdbc.user" value="root"/><property name="javax.persistence.jdbc.password" value="2001"/><property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/><property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/springdata_jpa?useUnicode=true&amp;useSSL=false&amp;characterEncoding=UTF-8"/><!-- 配置JPA實現方 (hibernate) 的配置信息顯示sql : false|true自動創建數據庫表: hibernate.hbm2ddl.autocreate: 程序運行時創建數據庫表(如果有表,先刪除在創建)update: 程序運行時創建表(如果有表,不會創建表)none: 不會創建表--><property name="hibernate.show_sql" value="true"/><property name="hibernate.hbm2ddl.auto" value="update"/><property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57InnoDBDialect"/></properties></persistence-unit></persistence>

3.創建測試類

package com.kuang.test;import com.kuang.pojo.Customer;
import org.junit.Before;
import org.junit.Test;import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.xml.soap.SAAJMetaFactory;public class JpaTest {private EntityManagerFactory factory;@Beforepublic void before() {//EntityManagerFactory 創建工廠 對應 sqlSessionFactory  用來創建 entityManagerfactory = Persistence.createEntityManagerFactory("hibernateJPA");}@Testpublic void insert() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟Customer customer = new Customer();customer.setCustName("劉備");customer.setCustAddress("錦州");entityManager.persist(customer);transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}@Testpublic void select() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟Customer customer = entityManager.find(Customer.class, 1L);
//            Customer customer = entityManager.getReference(Customer.class, 1L);//延遲查詢
//            System.out.println("=======");System.out.println(customer);transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}@Testpublic void update() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟Customer customer = new Customer();customer.setCustId(9L);customer.setCustName("lzl");customer.setCustAddress("為魯斯");/*** 如果指定了主鍵:*          更新 :1. 先查詢 看是否有變化*         *如果有變化 更新  如果沒有變化 就不更新* 如果沒有指定主鍵:*         插入:*///存在即修改, 不存在就添加//注意: 修改是覆蓋操作,你沒給的值,就全給你覆蓋為null// 如果你不想讓他查一遍,你可以自己寫JPQL語句進行添加或者修改Customer merge = entityManager.merge(customer);transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}@Testpublic void update_JPQL() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟String jpql="update Customer set custName=:custName , custAddress=:custAddress where custId=:id";entityManager.createQuery(jpql).setParameter("custName","張杰").setParameter("custAddress","廣東").setParameter("id",3L).executeUpdate();transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}@Testpublic void test_SQL() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟String sql="update tb_customer set cust_name=:custName , cust_address=:custAddress where  cust_id=:id";entityManager.createNativeQuery(sql).setParameter("custName","謝娜").setParameter("custAddress","湖南").setParameter("id",3L).executeUpdate();transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}@Testpublic void delete() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟Customer customer = entityManager.find(Customer.class, 3L);entityManager.remove(customer);// 這樣刪除,是刪除游離狀態的,會拋異常不允許這樣操作  IllegalArgumentException: Removing a detached instance com.kuang.pojo.Customer#3transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}@Testpublic void template() {//其實底層實現還是hibernate// entityManager 相當于 sqlSession 代碼與數據庫之間的橋梁EntityManager entityManager = null;EntityTransaction transaction=null;try {entityManager = factory.createEntityManager();transaction = entityManager.getTransaction();//獲取事務對象transaction.begin();//事務開啟transaction.commit();//事務提交} catch (Exception e) {e.printStackTrace();transaction.rollback();//事務回滾} finally {if (entityManager!=null){entityManager.close();//關閉連接}}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/211888.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/211888.shtml
英文地址,請注明出處:http://en.pswp.cn/news/211888.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

TCP三次握手、四次揮手及狀態轉換詳解

1.什么是TCP協議&#xff1f; 傳輸控制協議&#xff08;TCP&#xff0c;Transmission Control Protocol&#xff09;是一種面向連接的、可靠的、基于字節流的傳輸層通信協議&#xff0c;位于網絡OSI七層模型的第四層&#xff0c;IP協議一起工作&#xff0c;TCP層是位于IP層之上…

(Spring學習07)Spring之啟動刷新過程源碼解析

概述 通常&#xff0c;我們說的Spring啟動&#xff0c;就是構造ApplicationContext對象以及調用refresh()方法的過程。 首先&#xff0c;Spring啟動過程主要做了這么幾件事情&#xff1a; 構造一個BeanFactory對象解析配置類&#xff0c;得到BeanDefinition&#xff0c;并注冊…

CrystalDiskInfo中文版(硬盤檢測工具) v9.1.1.0 綠色漢化版-供大家學習研究參考

更新內容 重新支持三星SATA SSD壽命報告 增加對ZHITAI SC001的支持 新增SK hynix Gold S31支持 增加了KLEVV NEO N610的支持。 改進的Micron/Crucial SATA SSD支持 已更改 卸載程序將顯示一個確認對話框&#xff0c;用于刪除設置。 強大功能 1.擁有多國語言&#xff0c;…

27 動態規劃解最大子序和

問題描述&#xff1a;給定一個整數數組nums&#xff0c;找到一個具有最大和的連續子數組(子數組最少含有一個元素)&#xff0c;返回其最大和。 動態規劃求解&#xff1a;定義dp[i]表示以i元素為結尾的最大和&#xff0c;如果dp[i-1]小于零的話&#xff0c;dp[i]nums[i],否則dp…

React-hook-form-mui(三):表單驗證

前言 在上一篇文章中&#xff0c;我們介紹了react-hook-form-mui的基礎用法。本文將著重講解表單驗證功能。 react-hook-form-mui提供了豐富的表單驗證功能&#xff0c;可以通過validation屬性來設置表單驗證規則。本文將詳細介紹validation的三種實現方法&#xff0c;以及如何…

ts中type和interface類型聲明的區別

1. 寫法上 type 使用關鍵字 type 進行聲明。 interface 使用關鍵字 interface 進行聲明。 // 使用 type type MyType {param: string; };// 使用 interface interface MyInterface {param: string; }2. 可合并性 interface 具有可合并性&#xff0c;允許在同一作用域內多次…

045:Vue讀取本地上傳JSON文件,導出JSON文件方法

第045個 查看專欄目錄: VUE ------ element UI 專欄目標 在vue和element UI聯合技術棧的操控下&#xff0c;本專欄提供行之有效的源代碼示例和信息點介紹&#xff0c;做到靈活運用。 &#xff08;1&#xff09;提供vue2的一些基本操作&#xff1a;安裝、引用&#xff0c;模板使…

jquery手寫廣告輪播圖,無限循環功能

說明 在很多情況下&#xff0c;我們都需要開發廣告輪播圖&#xff0c;當我們進行頁面的功能開發時&#xff0c;采用輪播圖來實現也行&#xff0c;但是很多情況下&#xff0c;我們只需要簡單的控制輪播循環輪播展示即可&#xff0c;所以用jq開開發廣告輪播波&#xff0c;自定義…

spring更加松散的獲取bean的方式ObjectProvider

概述 ObjectProvider直譯就是對象提供者; 平時從spring中獲取bean都是調用beanFactory.getBean()方法&#xff0c;如果bean不存在則會直接拋異常; 從spring 4.3開始引入了org.springframework.beans.factory.ObjectProvider接口,其提供了若干的方法&#xff0c;可以更松散的…

Idea 插件開發: Swing Designer設計器創建的組件全部為空問題記錄

問題現象 通過Swing 設計器創建的對象, Swing組件全部是空的, 導致ToolWindowFactory工廠的實現類調用時候出現了空指針異常 如下方式創建的 問題分析 問題出現時候, 同時給我生成了一個createUIComponents的私有方法, 由于個人當時理解有誤, 把他當成了初始化方法, 在里面…

Oracle高可用一家老小全在這里

&#x1f4e2;&#x1f4e2;&#x1f4e2;&#x1f4e3;&#x1f4e3;&#x1f4e3; 哈嘍&#xff01;大家好&#xff0c;我是【IT邦德】&#xff0c;江湖人稱jeames007&#xff0c;10余年DBA及大數據工作經驗 一位上進心十足的【大數據領域博主】&#xff01;&#x1f61c;&am…

用Java實現一對一聊天

目錄 服務端 客戶端 服務端 package 一對一用戶; import java.awt.BorderLayout; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; imp…

s3-dist-cp 介紹教程示例使用方法

s3-dist-cp 是 AWS EMR 內置的用于 S3 和 HDFS 之間文件拷貝的專用工具,與 Hadoop 的 distcp 類似,也是通過 Map-Reduce 作業的方式實現分布式的文件復制(distcp 就是 distributed copy 分布式拷貝的意思)。 s3-dist-cp 并不是一個簡單的在 S3 和 HDFS 之間拷貝文件的工具…

SpringBoot中MyBatis-Flex的集成和使用

一、MyBatis-Flex 是什么? MyBatis-Flex是一個基于MyBatis的數據訪問框架&#xff0c;專門為Flex應用程序而設計的。它提供了一種靈活而高效的方式來處理Flex應用程序中的數據訪問&#xff0c;可以輕松地連接到各種數據源&#xff0c;并提供了一些方便的工具和功能&#xff0c…

虛擬機和主機間復制粘貼

文章目錄 前言一、版本介紹二、安裝工具1.確認配置2.安裝工具3.重啟 總結 前言 在Windows中使用虛擬機&#xff0c;可以很方便地linux&#xff0c;就像是在本地操作服務器一樣。 一、版本介紹 虛擬機&#xff1a;VMware 15 操作系統&#xff1a;CentOS 7 二、安裝工具 1.確…

delphi android打開外部文件,報錯android.os.FileUriExposedException解決方法

Android 7.0強制啟用了被稱作 StrictMode的策略&#xff0c;帶來的影響就是你的App對外無法暴露file://類型的URI了。 如果你使用Intent攜帶這樣的URI去打開外部App(比如&#xff1a;打開系統相機拍照)&#xff0c;那么會拋出FileUriExposedException異常。 Delphi 為Android…

C++(14):通過tuple在構造對象時注入類型不確定的對象/插件

有的時候我們需要在構建對象時注入一系列類型不確定的對象或插件,怎么才能實現呢? #include <iostream> #include <string> #include <tuple>using namespace std;class A{ public:A(int a) : m_a(a){cout<<"construct A:"<<m_a<…

windows系統安裝RocketMQ_dashboard

1.下載源碼 按照官網說明下載源碼 官網 官網文檔 2.源碼安裝 2.1.① 編譯rocketmq-dashboard 注釋掉報錯的maven插件frontend-maven-plugin、maven-antrun-plugin mvn clean package -Dmaven.test.skiptrue2.2.② 運行rocketmq-dashboard java -jar target/rocketmq-…

Qt基礎-connect函數詳解

本文詳解Qt的connect函數用法。 目錄 定義 形式 函數原型 實例說明 定義 Qt中的信號槽為核心內容,一定要熟練掌握。鏈接信號使用connect函數。 QObject::connect函數,顧名思義,鏈接函數,作用是鏈接信號(signal)和槽(

tamcat亂碼

學習springmvc時tamcat亂碼 ①、啟動時tomcat控制臺亂碼 解決方法是&#xff1a;1、先把idea設置里的默認字節碼改成utf-8 ? 2、把idea顯示編碼改成utf-8&#xff0c;在末尾加上&#xff08; -Dfile.encodingUTF-8&#xff09; ? 3、最后重啟idea 加上這個 -Dfile.encodingU…