Question: If entity.getHistory() is null following code snippet:

(getEntityManager() returns spring injected EntityManager, database field history type is: text or varchar2(2000)

```
Query query = getEntityManager().createNativeQuery("insert into table_name(..., history, ....) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
[...]
.setParameter(6, entity.getHistory())
[...]

query.executeUpdate();

```

Gives strange exception:

```
17/11/11 06:26:09:009 [pool-2-thread-1]  WARN util.JDBCExceptionReporter:100 - SQL Error: 0, SQLState: 42804
17/11/11 06:26:09:009 [pool-2-thread-1] ERROR util.JDBCExceptionReporter:101 - ERROR: **column "history" is of type text but expression is of type bytea**

```

Hint: You will need to rewrite or cast the expression.

Problem occurred only in this configuration:  

OS: CentOS release 5.6 (Final)  

Java: 1.6.0\_26  

DB: PostgreSQL 8.1  

JDBC Driver: postgresql-9.1-901.jdbc4  

Application Server: apache-tomcat-6.0.28

Everything is working fine on few other configurations or when history is empty string.
Same statement executed from pgAdmin works fine.

I guess problem is in PostgreSQL JDBC driver, is there some sensible reason to treat null string as a bytea value? Maybe some strange changes between Postgres 8 and 9?

Answer: 
You can cast the parameter to a proper type in the query. I think this solution should work for other databases, too.

Before:

```java
@Query("SELECT person FROM people person"
     + " WHERE (?1 IS NULL OR person.name = ?1)")
List<Person> getPeopleWithName(final String name);

```

After:

```java
@Query("SELECT person FROM people person"
     + " WHERE (?1 IS NULL OR person.name = cast(?1 as string))")
List<Person> getPeopleWithName(final String name);

```

Also works for `LIKE` statements:

```sql
person.name LIKE concat('%', cast(?1 as string), '%')

```

and with numbers (here of type `Double`):

```sql
person.height >= cast(cast(?1 as string) as double)

```
Had this issue in my springboot application, with postgres and hibernate.
I needed to supply date from/to parameters, with possible nulls in every combination.

Excerpt of the query :

```
   ...
        WHERE  f.idf = :idCat
        AND f.supplier = TRUE
        AND COALESCE (pc.datefrom, CAST('2000-1-1' AS DATE) ) <= COALESCE (:datefrom, now())
        AND COALESCE (pc.dateto, CAST('2200-12-31' AS DATE) ) >= COALESCE (:dateto, now())

```

Dao call :

```
@Transactional(readOnly = true)
public List<PriceListDto> ReportCatPriceList(Long idk, Date dateFrom, Date dateTo) {
    Query query = EM.createNativeQuery(queryReport, PersonProductsByDay.class)
        .setParameter("idCat", idk)
        .setParameter("datefrom", dateFrom, TemporalType.DATE)
        .setParameter("dateto", dateTo, TemporalType.DATE);

    return query.getResultList();
}

```