【发布时间】:2020-01-16 15:55:20
【问题描述】:
需要知道如何使用 HQL 和 select 进行插入,并且该 select 包含一个联合。这是我的测试用例
create table simple_author (
id bigint generated by default as identity,
first_name varchar(255),
last_name varchar(255),
primary key (id))
@Entity
public class SimpleAuthor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
private String firstName;
private String lastName;}
假设要求是插入 2 个作者,如果一个作者因某种原因失败,另一个则不会保存在数据库中。
只使用 SQL,如果是 Oracle 或 H2,我可以做到 插入 simple_author(first_name, last_name) select ‘bob’, ‘smith’ from dual union select ‘frank’, ‘brown’ from dual
或者如果使用 SQL Server: 插入 simple_author(first_name, last_name) select ‘bob’, ‘smith’ union select ‘frank’, ‘brown’
假设 Bob Smith 和 Frank Brown 由用户在 UI 中输入数据提供。
看着https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#hql-insert 似乎支持一个简单的案例。 似乎有几个问题: 在这种情况下进行联合和要添加的值列表 bob smith 和 frank brown 对于工会已经尝试了一些解决方案,如线程中所见
和
How to execute query with union in hibernate?
它们充其量似乎只是接近所需的。 所以问题是如何写: 插入 simple_author(first_name, last_name) 选择'bob','smith' from dual union select'frank','brown' from dual 在hsql中
【问题讨论】: