带有主体和三元运算符的Spring @Query

时间:2016-03-18 14:04:50

标签: spring-boot spring-data-jpa spring-el ternary

public bool ExportExcelToSql (DataTable DT)
    {
        bool result = false;
        tableColumns = "*";
        try
        {
            using (var connection = new OleDbConnection(_excelConnectionString))
            {
                connection.Open();
                DataTable dt = null;
                dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                _excelSheetName = dt.Rows[0]["TABLE_NAME"].ToString();
                var command = new OleDbCommand("Select " + tableColumns + " FROM [" + _excelSheetName + "]", connection);
                command.CommandTimeout = 6000;
                using (DbDataReader dr = command.ExecuteReader())
                {
                    string conString = _sqlConnectionString;
                    var sqlConn = new SqlConnection(conString);
                    sqlConn.Open();

                    using (var bulkCopy = new SqlBulkCopy(sqlConn))
                    {
                        bulkCopy.BulkCopyTimeout = 6000;
                        bulkCopy.DestinationTableName = tableName.ToString();
                        for (int i = 0; i < DT.Rows.Count; i++)
                        {
                            bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(DT.Rows[i][0].ToString(), DT.Rows[i][1].ToString(),));
                        }
                        bulkCopy.WriteToServer(dr);
                    }
                    result = true;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return result;
    }

如果用户是匿名用户,则此方法旨在返回当前用户/人或没有任何内容(数据库中没有id = 0的用户)。它在第一种情况下工作正常,但是当用户是匿名用户时会出错:

  

org.hibernate.QueryException:并非所有命名参数都已设置:   [1] [从p中选择p,其中p.id =?1)]

现在看来它需要一些参数,但为什么呢?不应该是查询

@Query("select p from Person p where p.id=?#{principal=='anonymousUser'?0:principal.id})")
public Person getCurrentUser();

1 个答案:

答案 0 :(得分:0)

如果用null替换0

,它似乎会起作用