Error: Hexadecimal string contains non-hex character for enumerated field - enums

I've got an error
Caused by: org.h2.jdbc.JdbcSQLDataException: Hexadecimal string contains non-hex character: "SWEDISH_MARKET"; SQL statement:
when I pass an enum as parameter to query
Entity has this enum as field.
Field has bellow annotations
#Column(name = "market", nullable = false)
#Enumerated(EnumType.STRING)
private Market type;
query:
#Query(value = "SELECT count(*) " +
"FROM Statements statements WHERE " +
"market = :market",
nativeQuery = true)
long countStatements(#Param("licenseMarket") Market market);
Previously everything was parsed to String and casted in postgres market = (cast :market as text)
Invoking countStatements(Market.SWEDISH_MARKET) throws the exception

You have to use JPQL, then it parse enums automatia

The problem is enum was parsed automatically to the number, regardless column type is text.
Solutions are:
invoke on enum method .name() and pass a param as String,
use SpEL :#{#market?.name()},

Related

How to add optional parameter in JPQL?

How to use/add optional parameter in JPQL?
#Query(value = "SELECT stud FROM Student stud where stud.name = :studentName AND stud.age IN :studentAgeList")
List<Student> getStudents(
#Param("studentName ") String studentName,
#Param("studentAgeList") List<Integer> studentAgeList
)
How to make studentAgeList parameter in above query ?
I tried below :
#Query(value = "SELECT stud FROM Student stud where stud.name = :studentName AND (:studentAgeList IS NULL OR stud.age IN :studentAgeList))
List<Student> getStudents(
#Param("studentName ") String studentName,
#Param("studentAgeList") List<Integer> studentAgeList
)
But getting error : unexpected AST node:
Tried above but getting error
JPQL does not support optional parameters, you can use overload methods with different queries or criteria API or JPA specifications.
may be get answer here: Set optional parameters in JPQL Query

Named Query with map values in Spring Data JPA

i have a hashmap like which has key value pair such as :
testMap = new HashMap(){{
put(iD, sID);
put(lEVEL, sLevel);
put(tYPE, sType);
put(vALUE, sValue);
Now i have my entity Class which has fields like
#Column(name = "ID")
private String id;
#Column(name = "LEVEL")
private String level;
#Column(name = "PROGRAM")
private String program;
#Column(name = "TYPE")
private String type;
#Column(name = "VALUE")
private String value;
#Column(name = "STARTDATE")
private Date start;
Now i need to form a named query where for each column i have to set values by extracting them from map key value pair (something like this :tesMap.get(iD) and setting in ID column) and also comparing the start date with the current date and setting the largest date in startdate column .
Tried the following using Named query but didn't work .
#Query(value = "SELECT * FROM OVERRIDES s " +
"WHERE s.ID =?1 AND s.LEVEL=?2 AND s.TYPE=?3 AND s.VALUE=?4", nativeQuery = true)
Also ,unable to decide how to compare dates in this select query .
Comparing the dates can be easily done with Date.after() method.
E.g.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2022-07-01");
Date date2 = sdf.parse("2022-08-31");
if(date1.after(date2)) {
//set largest date in date column
}
As for the rest question, please provide the whole Entity, or maybe more infos about the query
In SQL, you can compare dates/timestamps with relational operators >, <, >=, <= i.e.
#Query(value = "SELECT * FROM OVERRIDES s " +
"WHERE s.ID =?1 AND s.LEVEL=?2 AND s.TYPE=?3 AND s.VALUE>=?4", nativeQuery = true)

HQL query returing null value on use of like operator for search

query = genericDAOImpl.getHibernateSession().createQuery("select t from ticket t where createdBy=:user and t.subject like concat("%", :summary, "%")
.setParameter("user", userId)
.setParameter("summary", inputBean.getSummary);
this is my query when I search for some values it returns the proper output but when I give null value for the search field it returns empty list actually it should return all the values when the search field is empty
You should just use a plain named placeholder for the predicate of the LIKE expression, and then bind the wildcard string from the Java side:
String sql = "select t from ticket t where createdBy = :user and t.subject like :summary";
query = genericDAOImpl.getHibernateSession().createQuery(sql);
query.setParameter("user", userId);
query.setParameter("summary", "%" + inputBean.getSummary + "%");

Database Oracle, Query Date String JPA Repository Crud Repository, Java 8

NOTE: I can't put some privated code (Database or Java Code).
I have in the Database
CREATE TABLE "SCHEMA"."ENTITY"
(
"HCODFECREGISTR" DATE,
... BLABLA
)
The Entity
import java.util.Date;
public class Entity implements java.io.Serializable {
private Date hcodfecregistr;
....
}
In the Repository Interface
using
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface EntityRepository extends CrudRepository<Entity, Long>,
JpaRepository<Entity, Long> {
public static final String USING_STRING
= " SELECT enti FROM Entity enti WHERE "
+ " (enti.hcodfecregistr BETWEEN TO_DATE(:stringIni,'dd/MM/yyyy hh24:mi') AND TO_DATE(:stringEnd,'dd/MM/yyyy hh24:mi'))";
#Query(value = USING_STRING)
List<Object[]> getEntityUsingString(
#Param("stringIni") String stringIni, #Param("stringEnd") String stringEnd);
public static final String USING_DATE
= " SELECT enti FROM Entity enti WHERE "
+ " (enti.hcodfecregistr BETWEEN :dateIni AND :dateIni) ";
#Query(value = USING_DATE)
List<Object[]> getEntityUsingDate(
#Param("dateIni") Date dateIni, #Param("dateEnd") Date dateEnd);
}
Now I want to perform a query.
Date fecha = //some java.util.Date
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date dateIni = calendar.getTime();
calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date dateEnd = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String stringIni = dateFormat.format(fecha) + " 00:00";
String stringEnd = dateFormat.format(fecha) + " 23:59";
Works!
List<Object[]> listaObjects = theRepository.getEntityUsingString(stringIni, stringEnd);
Fails! It does not bring me results (but it also does not show any error).
List<Object[]> listaObjects = theRepository.getEntityUsingDate(dateIni, dateEnd);
Question:
I want to understand Why using the same fecha (java.util.Date) the method getEntityUsingString works, but using the method getEntityUsingDate fails (
When I set the range using Date it does not bring me results, whereas when I set the range with String it does.).
In my opinion, it should yield the same result that complies with the range of dates.
What is the problem?
You did not write what error it was, so it's only my guess that the most likely error in this case is:
ORA-01861: literal does not match format string.
If this is the case, then the reason is that you are passing to the query two values of date type:
Date dateIni = calendar.getTime();
.....
Date dateEnd = calendar.getTime();
.....
theRepository.getEntityUsingDate(dateIni, dateEnd);
these values are bind to this parameters :stringIni and :stringEnd
BETWEEN TO_DATE(:stringIni,'dd/MM/yyyy hh24:mi') AND TO_DATE(:stringEnd,'dd/MM/yyyy hh24:mi')
Since TO_DATE( char, [format] ) functions expects CHAR (string) as a first parameter, but gets a date, then according to rules explained in this documentation see section: implicit conversion
The following rules govern implicit data type conversions: .... ....
When you use a SQL function or operator with an argument of a data
type other than the one it accepts, Oracle converts the argument to
the accepted data type.
it does an implicit conversion from date to string using TO_CHAR function.
This function uses the default date language from a session to format strings, so depending of this settings the date may be converted to something like 12/15/54, 19-06-11 12:23 PM, JUN 23, 2019 13:20 AM +01 etc.
This string 12/15/54 is then passed to TO_DATE(:stringIni,'dd/MM/yyyy hh24:mi'), and because this sting doesnt match format string, the error is thrown: ORA-01861: literal does not match format string

How to pass Byte value to JPQL in Spring?

I have an Interface wich
extends JpaRepository
I have method in it:
#Query("SELECT a FROM ArticlesEntity a " +
"WHERE ((:approved = 2 ) or (a.approved = :approved)) ")
Page<ArticlesEntity> filterByAllPage(
#Param("approved") Byte approved,
Pageable pageable);
When this method is invoked I have an exeption:
java.lang.IllegalArgumentException: Parameter value [2] did not match expected type [java.lang.Integer (n/a)]
When I change
(:approved = 2 )
to
(:approved is null)
or
#Param("approved") Byte approved
to
#Param("approved") Integer approved
or
"WHERE ((:approved = 2 ) or (a.approved = :approved))"
to
"WHERE (a.approved = :approved) "
it works.
It seems that should be something like
(:approved = (byte) 2 )
or
(:approved=2.byteValue())
but both didn't work also.
Is there any way to use Byte here or it's better to switch to Integer ?
The database is MySQL and it has table "articles" with column "approved" of "TINYINT(1)" type.

Resources