LocalContainerEntityManagerFactoryBean源码

是 Spring Data JPA 中的一个类,它用于创建 EntityManagerFactory 的实例,获取EntityManager实例

public class LocalContainerEntityManagerFactoryBean extends AbstractEntityManagerFactoryBeanimplements ResourceLoaderAware, LoadTimeWeaverAware {//主要方法public void afterPropertiesSet() throws PersistenceException {//是一个用于获取JPA持久化单元的接口,主要用于解决多配置文件情况。默认实现是DefaultPersistenceUnitManager//用于指定数据源、JPA配置文件、持久化单元名字、持久化实现厂商类以及特定属性等PersistenceUnitManager managerToUse = this.persistenceUnitManager;if (this.persistenceUnitManager == null) {this.internalPersistenceUnitManager.afterPropertiesSet();managerToUse = this.internalPersistenceUnitManager;}//它由容器实现并用于创建 EntityManagerFactory。这个接口提供了关于持久化单元的信息,包括数据源、JPA 配置文件、持久化单元名称、持久化实现厂商类以及特定属性等//通过 PersistenceUnitInfo,容器可以向 JPA 提供商提供有关持久化单元的详细信息,以便后者能够根据这些信息创建适当的 EntityManagerFactory。这对于应用程序的持久化逻辑至关重要,因为它决定了如何将数据映射到数据库以及如何执行各种持久化操作this.persistenceUnitInfo = determinePersistenceUnitInfo(managerToUse);JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter();if (jpaVendorAdapter != null && this.persistenceUnitInfo instanceof SmartPersistenceUnitInfo) {String rootPackage = jpaVendorAdapter.getPersistenceProviderRootPackage();if (rootPackage != null) {((SmartPersistenceUnitInfo) this.persistenceUnitInfo).setPersistenceProviderPackageName(rootPackage);}}super.afterPropertiesSet();}
}
//创建Native EntityManangerFactory
protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {Assert.state(this.persistenceUnitInfo != null, "PersistenceUnitInfo not initialized");PersistenceProvider provider = getPersistenceProvider();if (provider == null) {String providerClassName = this.persistenceUnitInfo.getPersistenceProviderClassName();if (providerClassName == null) {throw new IllegalArgumentException("No PersistenceProvider specified in EntityManagerFactory configuration, " +"and chosen PersistenceUnitInfo does not specify a provider class name either");}Class<?> providerClass = ClassUtils.resolveClassName(providerClassName, getBeanClassLoader());provider = (PersistenceProvider) BeanUtils.instantiateClass(providerClass);}if (logger.isDebugEnabled()) {logger.debug("Building JPA container EntityManagerFactory for persistence unit '" +this.persistenceUnitInfo.getPersistenceUnitName() + "'");}EntityManagerFactory emf =provider.createContainerEntityManagerFactory(this.persistenceUnitInfo, getJpaPropertyMap());postProcessEntityManagerFactory(emf, this.persistenceUnitInfo);return emf;}

AbstractEntityManagerFactoryBean

public void afterPropertiesSet() throws PersistenceException {//JpaVendorAdapter是一个接口,用于设置实现厂商JPA实现的特定属性JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter();if (jpaVendorAdapter != null) {if (this.persistenceProvider == null) {this.persistenceProvider = jpaVendorAdapter.getPersistenceProvider();}PersistenceUnitInfo pui = getPersistenceUnitInfo();Map<String, ?> vendorPropertyMap = (pui != null ? jpaVendorAdapter.getJpaPropertyMap(pui) :jpaVendorAdapter.getJpaPropertyMap());if (!CollectionUtils.isEmpty(vendorPropertyMap)) {vendorPropertyMap.forEach((key, value) -> {if (!this.jpaPropertyMap.containsKey(key)) {this.jpaPropertyMap.put(key, value);}});}if (this.entityManagerFactoryInterface == null) {this.entityManagerFactoryInterface = jpaVendorAdapter.getEntityManagerFactoryInterface();if (!ClassUtils.isVisible(this.entityManagerFactoryInterface, this.beanClassLoader)) {this.entityManagerFactoryInterface = EntityManagerFactory.class;}}if (this.entityManagerInterface == null) {this.entityManagerInterface = jpaVendorAdapter.getEntityManagerInterface();if (!ClassUtils.isVisible(this.entityManagerInterface, this.beanClassLoader)) {this.entityManagerInterface = EntityManager.class;}}if (this.jpaDialect == null) {this.jpaDialect = jpaVendorAdapter.getJpaDialect();}}//构建EntityManagerFactory//创建一个本地的EntityManagerFactoryAsyncTaskExecutor bootstrapExecutor = getBootstrapExecutor();if (bootstrapExecutor != null) {this.nativeEntityManagerFactoryFuture = bootstrapExecutor.submit(this::buildNativeEntityManagerFactory);}else {this.nativeEntityManagerFactory = buildNativeEntityManagerFactory();}//然后创建真正使用的EntityManagerFactorythis.entityManagerFactory = createEntityManagerFactoryProxy(this.nativeEntityManagerFactory);}
//这个才是我们真正需要的EntityManagerFactory
protected EntityManagerFactory createEntityManagerFactoryProxy(@Nullable EntityManagerFactory emf) {Set<Class<?>> ifcs = new LinkedHashSet<>();Class<?> entityManagerFactoryInterface = this.entityManagerFactoryInterface;if (entityManagerFactoryInterface != null) {ifcs.add(entityManagerFactoryInterface);}else if (emf != null) {ifcs.addAll(ClassUtils.getAllInterfacesForClassAsSet(emf.getClass(), this.beanClassLoader));}else {ifcs.add(EntityManagerFactory.class);}ifcs.add(EntityManagerFactoryInfo.class);try {return (EntityManagerFactory) Proxy.newProxyInstance(this.beanClassLoader,ClassUtils.toClassArray(ifcs), new ManagedEntityManagerFactoryInvocationHandler(this));}catch (IllegalArgumentException ex) {if (entityManagerFactoryInterface != null) {throw new IllegalStateException("EntityManagerFactory interface [" + entityManagerFactoryInterface +"] seems to conflict with Spring's EntityManagerFactoryInfo mixin - consider resetting the "+"'entityManagerFactoryInterface' property to plain [javax.persistence.EntityManagerFactory]", ex);}else {throw new IllegalStateException("Conflicting EntityManagerFactory interfaces - " +"consider specifying the 'jpaVendorAdapter' or 'entityManagerFactoryInterface' property " +"to select a specific EntityManagerFactory interface to proceed with", ex);}}}
Object invokeProxyMethod(Method method, @Nullable Object[] args) throws Throwable {if (method.getDeclaringClass().isAssignableFrom(EntityManagerFactoryInfo.class)) {return method.invoke(this, args);}else if (method.getName().equals("createEntityManager") && args != null && args.length > 0 &&args[0] == SynchronizationType.SYNCHRONIZED) {// JPA 2.1's createEntityManager(SynchronizationType, Map)// Redirect to plain createEntityManager and add synchronization semantics through Spring proxyEntityManager rawEntityManager = (args.length > 1 ?getNativeEntityManagerFactory().createEntityManager((Map<?, ?>) args[1]) :getNativeEntityManagerFactory().createEntityManager());postProcessEntityManager(rawEntityManager);return ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, true);}// Look for Query arguments, primarily JPA 2.1's addNamedQuery(String, Query)if (args != null) {for (int i = 0; i < args.length; i++) {Object arg = args[i];if (arg instanceof Query && Proxy.isProxyClass(arg.getClass())) {// Assumably a Spring-generated proxy from SharedEntityManagerCreator:// since we're passing it back to the native EntityManagerFactory,// let's unwrap it to the original Query object from the provider.try {args[i] = ((Query) arg).unwrap(null);}catch (RuntimeException ex) {// Ignore - simply proceed with given Query object then}}}}// Standard delegation to the native factory, just post-processing EntityManager return valuesObject retVal = method.invoke(getNativeEntityManagerFactory(), args);if (retVal instanceof EntityManager) {// Any other createEntityManager variant - expecting non-synchronized semanticsEntityManager rawEntityManager = (EntityManager) retVal;postProcessEntityManager(rawEntityManager);//通过creator创建retVal = ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, false);}return retVal;}

ManagedEntityManagerFactoryInvocationHandler

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {switch (method.getName()) {case "equals":// Only consider equal when proxies are identical.return (proxy == args[0]);case "hashCode":// Use hashCode of EntityManagerFactory proxy.return System.identityHashCode(proxy);case "unwrap":// Handle JPA 2.1 unwrap method - could be a proxy match.Class<?> targetClass = (Class<?>) args[0];if (targetClass == null) {return this.entityManagerFactoryBean.getNativeEntityManagerFactory();}else if (targetClass.isInstance(proxy)) {return proxy;}break;}try {//真正执行创建的逻辑的方法return this.entityManagerFactoryBean.invokeProxyMethod(method, args);}catch (InvocationTargetException ex) {throw ex.getTargetException();}}}

ExtendedEntityManagerCreator

public static EntityManager createApplicationManagedEntityManager(EntityManager rawEntityManager, EntityManagerFactoryInfo emfInfo, boolean synchronizedWithTransaction) {return createProxy(rawEntityManager, emfInfo, false, synchronizedWithTransaction);
}
private static EntityManager createProxy(EntityManager rawEntityManager,EntityManagerFactoryInfo emfInfo, boolean containerManaged, boolean synchronizedWithTransaction) {Assert.notNull(emfInfo, "EntityManagerFactoryInfo must not be null");JpaDialect jpaDialect = emfInfo.getJpaDialect();PersistenceUnitInfo pui = emfInfo.getPersistenceUnitInfo();Boolean jta = (pui != null ? pui.getTransactionType() == PersistenceUnitTransactionType.JTA : null);return createProxy(rawEntityManager, emfInfo.getEntityManagerInterface(),emfInfo.getBeanClassLoader(), jpaDialect, jta, containerManaged, synchronizedWithTransaction);
}
private static EntityManager createProxy(EntityManager rawEm, @Nullable Class<? extends EntityManager> emIfc, @Nullable ClassLoader cl,@Nullable PersistenceExceptionTranslator exceptionTranslator, @Nullable Boolean jta,boolean containerManaged, boolean synchronizedWithTransaction) {Assert.notNull(rawEm, "EntityManager must not be null");Class<?>[] interfaces;if (emIfc != null) {interfaces = cachedEntityManagerInterfaces.computeIfAbsent(emIfc, key -> {Set<Class<?>> ifcs = new LinkedHashSet<>(4);ifcs.add(key);ifcs.add(EntityManagerProxy.class);return ClassUtils.toClassArray(ifcs);});}else {interfaces = cachedEntityManagerInterfaces.computeIfAbsent(rawEm.getClass(), key -> {Set<Class<?>> ifcs = new LinkedHashSet<>(ClassUtils.getAllInterfacesForClassAsSet(key, cl));ifcs.add(EntityManagerProxy.class);return ClassUtils.toClassArray(ifcs);});}return (EntityManager) Proxy.newProxyInstance((cl != null ? cl : ExtendedEntityManagerCreator.class.getClassLoader()),interfaces,new ExtendedEntityManagerInvocationHandler(rawEm, exceptionTranslator, jta, }

创建EntityManager流程

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/654886.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java 集合 04 综合练习-查找用户是否存在

练习、 代码&#xff1a; public class User{private String id;private String username;private int password;public User() {}public User(String id, String username, int password) {this.id id;this.username username;this.password password;}public String getI…

Linux提权:Docker组挂载 Rsync未授权 Sudo-CVE Polkit-CVE

目录 Rsync未授权访问 docker组挂载 Sudo-CVE漏洞 Polkit-CVE漏洞 这里的提权手法是需要有一个普通用户的权限&#xff0c;一般情况下取得的webshell权限可能不够 Rsync未授权访问 Rsync是linux下一款数据备份工具&#xff0c;默认开启873端口 https://vulhub.org/#/envir…

go-zero 统一返回

1、整体目录结构 2、全局处理主入口 package manageimport ("net/http""github.com/zeromicro/go-zero/rest/httpx" )type Body struct {Code int json:"code"Message string json:"message"Result interface{} jso…

RocketMq源码搭建报错No route info of this topic: TopicTest

原因 因为broker没有注册到namsesrv中&#xff0c;导致无法创建Topic 解决办法 启动Borker时&#xff0c;指定namsesrv地址 over!!!

防御保护常用知识

防火墙的主要职责在于&#xff1a;控制和防护 --- 安全策略 --- 防火墙可以根据安全策略来抓取流量之 后做出对应的动作 防火墙分类主要有四类&#xff1a; 防火墙吞吐量 --- 防火墙同一时间能处理的数据量多少 防火墙的发展主要经过以下阶段&#xff1b; 传统防火墙&#xf…

SpringBoot之JWT登录

JWT JSON Web Token&#xff08;JSON Web令牌&#xff09; 是一个开放标准(rfc7519)&#xff0c;它定义了一种紧凑的、自包含的方式&#xff0c;用于在各方之间以JSON对象安全地传输信息。此信息可以验证和信任&#xff0c;因为它是数字签名的。jwt可以使用秘密〈使用HNAC算法…

Element table组件内容\n换行

漂亮的页面总是让人心旷神怡&#xff0c;层次清晰的页面让用户操作起来也是易于上手及展示。 如下的页面展示就是非常low的&#xff1a;用户根本阅读其中的数据。 在这个页面&#xff0c;根据用户填写过程生成多次填写记录&#xff0c;如果不进行层次性的展示&#xff0c;数据…

qemu调试kernel启动(从第一行汇编开始)

一、背景 大部分qemu调试kernel 都是讲解从start_kernel开始设置断点&#xff0c;然后开启调试&#xff1b; 但是我们熟悉linux启动流程的伙伴肯定知道&#xff0c;在start_kernel之前还有一段汇编&#xff0c;包括初始化页表及mmu等操作&#xff0c; 这部分如何调试呢&#x…

漏洞原理linux操作系统的SqlMap工具的使用

漏洞原理linux操作系统的SqlMap工具的使用 Linux操作系统基础操作链接: 1024一篇通俗易懂的liunx命令操作总结(第十课)-CSDN博客 kali的IP地址:192.168.56.1 实操 # kali中使用sqlmap http://192.168.56.1/ sqlmap -u http://192.168.56.1/news/show.php?id46 sqlmap -u …

​ArcGIS Pro 如何批量删除字段

在某些时候&#xff0c;我们得到的图层属性表内可能会有很多不需要的字段&#xff0c;如果挨个去删除会十分的麻烦&#xff0c;对于这种情况&#xff0c;我们可以使用工具箱内的字段删除工具批量删除&#xff0c;这里为大家介绍一下使用方法&#xff0c;希望能对你有所帮助。 …

如何创建用户友好的软件产品说明书?(上:建议篇)

之前我有写过关于制作和编写用户友好的产品说明书需要注意哪些地方&#xff0c;以及有哪些方法可以比较快速制作编写产品说明书。但是有网友在后台私信我&#xff0c;说想要知道细化到软件的产品说明书需要注意什么&#xff1f;所以我打算将关于“软件产品说明书”的主题分成两…

IDEA常用插件(本人常用,不全)

文章目录 一、图标提示类插件1、Lombok插件&#xff08;用户配合lombok依赖的工具&#xff09;2、MybatisX插件3、GitToolBox4、VUE.js&#xff08;vue编程使用&#xff09;5、ESLint&#xff08;vue编程使用&#xff09; 二、代码自动生成插件1、EasyCode插件&#xff1a;自动…

Android中下载 HAXM 报错 Intel® HAXM installation failed,如何解决?

最近在搭建 Flutter 环境&#xff0c;但是在 Android Studio 中安装 Virtual Device 时&#xff0c;出现了一个 问题 Intel HAXM installation failed. To install Intel HAXM follow the instructions found at: https://github.com/intel/haxm/wiki/Installation-Instructio…

爬虫学习笔记-xpath的基本使用

html示例 基本使用 #导入包 #pip install lxmlfrom lxml import etree# xpath解析 # 1.本地文件 etree.parse # 2.服务器响应的数据 etree.HTML()tree etree.parse(baidu.html) # 获取所有的ul下的li标签 l1 tree.xpath(//ul/li) print(l1) print(len(l1))# 获取所有带有id的…

某大厂关于Linux系统相关面试题

一、Linux系统和Shell 1、写一个sed命令&#xff0c;修改/tmp/input.txt文件的内容&#xff0c;要求&#xff1a;(1) 删除所有空行&#xff1b;(2) 在非空行前面加一个"AAA"&#xff0c;在行尾加一个"BBB"&#xff0c;即将内容为11111的一行改为&#xff1…

安防监控项目

一、安防监控项目的概述 安防监控项目是指利用先进的技术手段对特定区域、场所或对象进行全天候、全方位的监控和管理&#xff0c;以确保安全和防范各类安全风险。随着科技的不断发展&#xff0c;安防监控项目已经从传统的简单监控摄像头向数字化、智能化方向发展。这些项目广…

代码随想录算法刷题训练营day19

代码随想录算法刷题训练营day19&#xff1a;LeetCode(404)左叶子之和、LeetCode(112)路径总和、LeetCode(113)路径总和 II、LeetCode(105)从前序与中序遍历序列构造二叉树、LeetCode(106)从中序与后序遍历序列构造二叉树 LeetCode(404)左叶子之和 题目 代码 /*** Definitio…

E. Vlad and a Pair of Numbers(位运算)

思路&#xff1a;如果x在这一位是1&#xff0c;说明a,b在这一位一个是1一个是0&#xff0c;我们默认a为1&#xff0c;b为0.. 对于n的一些位为0&#xff0c;那么a&#xff0c;b在这一位肯定相同。我们想&#xff0c;如果a和b的和右移一位与x相同&#xff0c;所以1的位置是相同的…

图算法 - 最短路径算法 (dijkstra) 迪克斯特拉算法

解决问题: 图中某个顶点到某一个顶点的最短路径 适用场景: 查找带权图的最短路径 代码设计: 首先定义一张图(邻接矩阵,二维数组方式实现) 生成一张图 迪克斯特拉算法实现 采用贪婪的方式,每次获取最短的一条路径,作为下次遍历的起点 使用visited 记录被访问过的节点避免…

网络安全04-sql注入靶场第一关

目录 一、环境准备 1.1我们进入第一关也如图&#xff1a; ​编辑 二、正式开始第一关讲述 2.1很明显它让我们在标签上输入一个ID&#xff0c;那我们就输入在链接后面加?id1 ​编辑 2.2链接后面加个单引号()查看返回的内容&#xff0c;127.0.0.1/sqli/less-1/?id1,id1 …