【问题标题】:How to perform an insert with a select statement to put in multiple rows with HQL如何使用选择语句执行插入以使用 HQL 放入多行
【发布时间】: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 对于工会已经尝试了一些解决方案,如线程中所见

Hibernate Union alternatives

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中

【问题讨论】:

    标签: hibernate hql


    【解决方案1】:

    至少对我而言,我使用的是 Spring,并且在撰写本文时并不知道在 DAO 中使用 @Transactional 注释的 Spring 将管理提交。发现实体管理器将根据是否发生异常来提交或回滚所有行,因此我可以达到提交“全部或全部”的目标。所以在我的情况下,代码是:

      // if an exception occurs then the transaction is rolled back there is not any
      // special code required.
      public List<SimpleAuthor> insertSimpleAuthors(List<SimpleAuthor> simpleAuthors) {   
       // try {
          //em.getTransaction().begin();
          for (SimpleAuthor entity : simpleAuthors) {
            em.persist(entity);     
          }
          //em.flush();
    //    } catch (Exception ex) {
    //      em.getTransaction().rollback();
    //      throw ex;
    //    }
        for (int i = 0; i < simpleAuthors.size(); i++) {
          //SimpleAuthor entity : simpleAuthors) {
          simpleAuthors.set(i, 
          em.createQuery("from SimpleAuthor where firstName = :firstName and lastName = :lastName",SimpleAuthor.class)
           .setParameter("firstName", simpleAuthors.get(i).getFirstName())
           .setParameter("lastName", simpleAuthors.get(i).getLastName())
           .getSingleResult()
           );
        }
        return simpleAuthors;
      }
    

    【讨论】:

      【解决方案2】:

      很遗憾,HQL/JPQL 不支持此功能。此类事情可以通过原生查询或像 FluentJPA 这样的技术来完成,后者在后台进行原生查询。

      【讨论】:

      • 是的..这也是我的结论。
      猜你喜欢
      • 2018-05-08
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      相关资源
      最近更新 更多