如果在HQL

时间:2017-05-03 17:12:00

标签: mysql sql database hibernate hql

我正在尝试在HQL中编写一个查询,如果该记录不存在(具有相同名称),则可以插入一条记录,以便在从多个线程完成时不会重复插入。

String hql = "INSERT INTO employee(emp_id, emp_name)"
        + " SELECT '100001' , 'John' " FROM employee
        + " WHERE NOT EXISTS (SELECT 1 from employee WHERE emp_name  = 'John')";

但是,未插入记录。我怀疑这是因为表是空的,尽管有NOT EXISTS子句,子查询返回0条记录。

注意 - ' 100001' ,'约翰' &安培;将以编程方式在实际查询字符串中替换。

3 个答案:

答案 0 :(得分:1)

任务:我们需要添加具有唯一 someId 的行。 但如果 someId 不是唯一的,则忽略。

现有数据(postgresql):

+------------------------------+
|            table_a           |
+------+--------------+--------|
|  id  |    some_id   |  data  |
+------+--------------+--------|
|   1  |    111111    |    a   |
|   2  |    111111    |    a   |
|   3  |    222222    |    b   |
|   4  |    333333    |    c   |
|   5  |    333333    |    c   |
+------------------------------+

解决(spring hibernate jpa hql):

@Repository
public interface TableARepository extends PagingAndSortingRepository<TableA, String>, JpaSpecificationExecutor<TableA> {
 
    @Transactional
    @Modifying
    @Query("INSERT INTO TableA (someId,  data) " +
           "SELECT             :someId, :data " + //SELECT - is alias for INSERT ... VALUES 
           "FROM TableA " + // just rudiment HQL for INSERT
           "WHERE NOT EXISTS " +
           "          (SELECT 1 " +
           "          FROM TableA " +
           "          WHERE someId = :someId) " +
           "          GROUP BY someId" //derived table with one row
    )
    void saveIfNotExists(@Param("someId") Long someId,
                         @Param("data") String data);

}

答案 1 :(得分:0)

您可以添加&#34;!&#34;像这样的运算符:

String hql = "INSERT INTO employee(emp_id, emp_name)"
        + " SELECT '100001' , 'John'  FROM employee "
        + " WHERE !EXISTS (SELECT 1 from employee WHERE emp_name  = 'John')";

答案 2 :(得分:0)

原因是您从空表中选择常量值。因此,您正在选择并插入零行。请注意,如果表有两行但它们都没有emp_name = 'John',则会插入两行。所以你应该从一个只有一行的表中选择:

INSERT INTO employee(emp_id, emp_name)
SELECT '100001' , 'John' 
FROM (select 1) as dummy -- derived table with one row
WHERE NOT EXISTS (SELECT 1 from employee WHERE emp_name  = 'John')

您可以使用(select 1) as dummy即时消息,而不是dual

正如我在评论中所写,您还可以将emp_name列定义为UNIQUE,然后使用INSERT IGNORE