如何在@GenericGenerator中显式指定schema

现在的情况是,在MySQL中有db1和db2两个数据库。项目使用Hibernate,可同时访问db1和db2,默认数据库为db1。表table2在db2中。且table2的主键名为ids,是自增长字段(Auto Increment)。

table2和ids的定义为:

@Entity
@Table(name = "table2", schema = "db2")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Table2 implements java.io.Serializable {
	private static final long serialVersionUID = 48L;

	@Id
	@Column(name = "ids")
	@GeneratedValue(generator = "idGenerator", strategy = GenerationType.IDENTITY)
	@GenericGenerator(name = "idGenerator", strategy = "increment")
	private Integer ids;

当向table2中保存数据时,会报错。原因是生成ids时,系统会查询table2中ids的最大值。语句是:

select max(ids) from table2

由于默认数据库是db1,因此查询的是db1.table2表。但table2表实际上在db2中,所以系统找不到该表,从而报错。

这就需要在@GenericGenerator中指定max查询语句的schema。通过检查错误信息,发现对应代码在org.hibernate.id.IncrementGenerator.configure()方法中,如下:

	public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
		returnClass = type.getReturnedClass();

		ObjectNameNormalizer normalizer =
				( ObjectNameNormalizer ) params.get( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER );

		String column = params.getProperty( "column" );
		if ( column == null ) {
			column = params.getProperty( PersistentIdentifierGenerator.PK );
		}
		column = dialect.quote( normalizer.normalizeIdentifierQuoting( column ) );

		String tableList = params.getProperty( "tables" );
		if ( tableList == null ) {
			tableList = params.getProperty( PersistentIdentifierGenerator.TABLES );
		}
		String[] tables = StringHelper.split( ", ", tableList );

		final String schema = dialect.quote(
				normalizer.normalizeIdentifierQuoting(
						params.getProperty( PersistentIdentifierGenerator.SCHEMA )
				)
		);
		final String catalog = dialect.quote(
				normalizer.normalizeIdentifierQuoting(
						params.getProperty( PersistentIdentifierGenerator.CATALOG )
				)
		);

		StringBuilder buf = new StringBuilder();
		for ( int i=0; i < tables.length; i++ ) {
			final String tableName = dialect.quote( normalizer.normalizeIdentifierQuoting( tables[i] ) );
			if ( tables.length > 1 ) {
				buf.append( "select max(" ).append( column ).append( ") as mx from " );
			}
			buf.append( Table.qualify( catalog, schema, tableName ) );
			if ( i < tables.length-1 ) {
				buf.append( " union " );
			}
		}
		if ( tables.length > 1 ) {
			buf.insert( 0, "( " ).append( " ) ids_" );
			column = "ids_.mx";
		}

		sql = "select max(" + column + ") from " + buf.toString();
	}

在初始化Table2实体类时,该方法就会执行。作用是生成对应数据库的select max语句。

在IncrementGenerator的注释中,有一段话:

Mapping parameters supported, but not usually needed: tables, column. (The tables parameter specified a comma-separated list of table names.)

说明在@GenericGenerator中,可以设置参数。在IncrementGenerator.configure()方法中,可以将这些参数读出来。读取参数的方法为params.getProperty("参数名")。例如:

params.getProperty( "column" )

就是读取column参数的值。对应读取schema的语句为:

final String schema = dialect.quote(
		normalizer.normalizeIdentifierQuoting(
		    params.getProperty( PersistentIdentifierGenerator.SCHEMA )
	)
);

schema的参数名就是PersistentIdentifierGenerator.SCHEMA,也就是"schema"。其他预置保留参数的值大都在org.hibernate.id.PersistentIdentifierGenerator中定义。如:

public interface PersistentIdentifierGenerator extends IdentifierGenerator {

	/**
	 * The configuration parameter holding the schema name
	 */
	public static final String SCHEMA = "schema";

	/**
	 * The configuration parameter holding the table name for the
	 * generated id
	 */
	public static final String TABLE = "target_table";

	/**
	 * The configuration parameter holding the table names for all
	 * tables for which the id must be unique
	 */
	public static final String TABLES = "identity_tables";

	/**
	 * The configuration parameter holding the primary key column
	 * name of the generated id
	 */
	public static final String PK = "target_column";

    /**
     * The configuration parameter holding the catalog name
     */
    public static final String CATALOG = "catalog";

	/**
	 * The key under whcih to find the {@link org.hibernate.cfg.ObjectNameNormalizer} in the config param map.
	 */
	public static final String IDENTIFIER_NORMALIZER = "identifier_normalizer";

在@GenericGenerator中设置parameter的方法为:

@Id
@Column(name = "ids")
@GeneratedValue(generator = "idGenerator", strategy = GenerationType.IDENTITY)
@GenericGenerator(name = "idGenerator", strategy = "increment", parameters = @Parameter(name = PersistentIdentifierGenerator.SCHEMA, value = "db2"))
private Integer ids;

这样就能在table2前加上正确的schema名称(db2),生成正确的查询语句:

select max(ids) from db2.table2

如果有多个参数,可以写为:

@GenericGenerator(name = "idGenerator", strategy = "increment", parameters = {
            @Parameter(name = PersistentIdentifierGenerator.SCHEMA, value = "db2"),
            @Parameter(name=PersistentIdentifierGenerator.CATALOG, value = "db2")

})

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Qt ORM模块使用说明

附源码&#xff1a;QxOrm是一个C库资源-CSDN文库 使用说明 把QyOrm文件夹拷贝到自己的工程项目下, 在自己项目里的Pro文件里添加include($$PWD/QyOrm/QyOrm.pri)就能使用了 示例test_qyorm.h写了表的定义,Test_QyOrm_Main.cpp中写了所有支持的功能的例子: 通过自动表单添加…

C++ ——string的模拟实现

目录 前言 浅记 1. reserve&#xff08;扩容&#xff09; 2. push_back&#xff08;尾插&#xff09; 3. iterator&#xff08;迭代器&#xff09; 4. append&#xff08;尾插一个字符串&#xff09; 5. insert 5.1 按pos位插入一个字符 5.2 按pos位插入一个字符串 …

CleanClip for Mac 剪切板 粘贴工具 历史记录 安装(保姆级教程,新手小白轻松上手)

CleanClip&#xff1a;革新macOS剪贴板管理体验 目录 功能概览 多格式历史记录保存智能搜索功能快速复制操作拖拽功能 安装指南 前期准备安装步骤 配置与使用 功能概览 多格式历史记录保存 CleanClip支持保存文本、图片、文件等多种格式的复制历史记录&#xff0c;为用户提…

C语言 | Leetcode C语言接雨水II

题目&#xff1a; 题解&#xff1a; typedef struct{int row;int column;int height; } Element;struct Pri_Queue; typedef struct Pri_Queue *P_Pri_Queue; typedef Element Datatype;struct Pri_Queue{int n;Datatype *pri_qu; };/*优先队列插入*/ P_Pri_Queue add_pri_que…

通信工程学习:什么是SNI业务节点接口

SNI&#xff1a;业务节点接口 SNI业务节点接口&#xff0c;全称Service Node Interface&#xff0c;是接入网&#xff08;AN&#xff09;和一个业务节点&#xff08;SN&#xff09;之间的接口&#xff0c;位于接入网的业务侧。这一接口在通信网络中扮演着重要的角色&#xff0c…

几种手段mfc140u.dll丢失的解决方法,了解mfc140u.dll

在使用Windows操作系统时&#xff0c;许多用户可能会遇到“找不到mfc140u.dll”或“mfc140u.dll未找到”的错误提示。这个错误通常是由于该文件丢失或损坏所致。本文将详细介绍mfc140u.dll文件的作用、丢失的原因及其解决方法&#xff0c;帮助您快速恢复系统的正常运行。 一、m…

2024年华为9月4日秋招笔试真题题解

2024年华为0904秋招笔试真题 二叉树消消乐好友推荐系统维修工力扣上类似的题--K站中转内最便宜的航班 二叉树消消乐 题目描述 给定原始二叉树和参照二叉树(输入的二叉树均为满二叉树&#xff0c;二叉树节点的值范围为[1,1000]&#xff0c;二叉树的深度不超过1000)&#xff0c…

Maven 解析:打造高效、可靠的软件工程

Apache Maven【简称maven】 是一个用于 Java 项目的构建自动化工具&#xff0c; 通过提供一组规则来管理项目的构建、依赖关系和文档。 1.Pre-预备知识&#xff1a; 1.1.Maven是什么&#xff1f; [by Maven是什么&#xff1f;有什么作用&#xff1f;Maven的核心内容简述_ma…

简化登录流程,助力应用建立用户体系

随着智能手机和移动应用的普及&#xff0c;用户需要在不同的应用中注册和登录账号&#xff0c;传统的账号注册和登录流程需要用户输入用户名和密码&#xff0c;这不仅繁琐而且容易造成用户流失。 华为账号服务(Account Kit)提供简单、快速、安全的登录功能&#xff0c;让用户快…

Zabbix自定义监控项与触发器

当我们需要获取某台主机上的数据时&#xff0c;直接利用 zabbix 提供的模板可以很方便的获得需要的数据,但是有些特别的数据&#xff0c;利用这些现有的模板或监控项是无法实现的&#xff0c;例如网站状态信息的监控、mysql数据库主从状态等信息。这是就需要自己定义键值和监控…

Java许可政策再变,Oracle JDK 17 免费期将结束!

原文地址&#xff1a;https://www.infoworld.com/article/3478122/get-ready-for-more-java-licensing-changes.html Oracle JDK 17的许可协议将于9月变更回Oracle Technology Network License Agreement&#xff0c;这将迫使用户重新评估他们的使用策略。 有句老话说&#xf…

小程序组件间通信

文章目录 父传子子传父获取组件实例兄弟通信 父传子 知识点&#xff1a; 父组件如果需要向子组件传递指定属性的数据&#xff0c;在 WXML 中需要使用数据绑定的方式 与普通的 WXML 模板类似&#xff0c;使用数据绑定&#xff0c;这样就可以向子组件的属性传递动态数据。 父…

java实际开发——数据库存储金额时用什么数据类型?(MySQL、PostgreSQL)

目录 java开发时金额用的数据类型——BigDecimal MySQL存储金额数据时用的数据类型是——decimal PostgreSQL存储金额数据时用的数据类型是——decimal 或 money java开发时金额用的数据类型——BigDecimal https://blog.csdn.net/Jilit_jilit/article/details/142180903?…

YOLOv5/v8 + 双目相机测距

yolov5/v8双目相机测距的代码&#xff0c;需要相机标定 可以训练自己的模型并检测测距&#xff0c;都是python代码 已多次实验&#xff0c;代码无报错。 非常适合做类似的双目课题&#xff01; 相机用的是汇博视捷的双目相机&#xff0c;具体型号见下图。 用的yolov5是6.1版本的…

ubuntu2204安装kvm

ubuntu2204安装kvm 前言一、检测硬件是否支持二、安装软件三、创建/管理虚拟机1、创建存储池2、qemu创建镜像3、xml文件运行虚拟机1、范文2、xml文件创建虚机3、创建虚机 4、克隆虚机5、创建快照6、脚本创建VNC连接 四、创建集群1、安装glusterfs2、加入集群删除节点 3、 创建卷…

深度剖析iOS渲染

iOS App 图形图像渲染的基本流程&#xff1a; 1.CPU&#xff1a;完成对象的创建和销毁、对象属性的调整、布局计算、文本的计算和排版、图片的格式转换和解码、图像的绘制。 2.GPU&#xff1a;GPU拿到CPU计算好的显示内容&#xff0c;完成纹理的渲染&#xff0c; 渲染完成后将渲…

基于YOLO深度学习和百度AI接口的手势识别与控制项目

基于YOLO深度学习和百度AI接口的手势识别与控制项目 项目描述 本项目旨在开发一个手势识别与控制系统&#xff0c;该系统能够通过摄像头捕捉用户的手势&#xff0c;并通过YOLO深度学习模型或调用百度AI接口进行手势识别。识别到的手势可以用来控制计算机界面的操作&#xff0…

使用 Elastic 和 LM Studio 的 Herding Llama 3.1

作者&#xff1a;来自 Elastic Charles Davison, Julian Khalifa 最新的 LM Studio 0.3 更新使 Elastic 的安全 AI Assistant 能够更轻松、更快速地与 LM Studio 托管模型一起运行。在这篇博客中&#xff0c;Elastic 和 LM Studio 团队将向你展示如何在几分钟内开始使用。如果你…

API - String 和 ArrayList

01 API是什么 答&#xff1a;API 全称 Application Programming Interfaace 应用程序编程接口。就是别人写好的一些程序&#xff0c;我们可以使用它们去解决相关问题。 02 为什么要学API 答&#xff1a;不要重复造轮子。Java已经有20多年的历史了&#xff0c;在这20多年里Ja…

图新地球-将地图上大量的地标点批量输出坐标到csv文件【kml转excel】

0.序 有很多用户需要在卫星影像、或者无人机航测影像、倾斜模型上去标记一些地物的位置&#xff08;如电线杆塔、重点单位、下水盖等&#xff09; 标记的位置最终又需要提交坐标文本文件给上级单位或者其他部门使用&#xff0c;甚至需要转为平面直角坐标。 本文的重点是通过of…