Convert query to hibernate criteria query - mysql

I have the following Sybase query,
select *
from dbo.translation_style_sheet t1
where t1.create_date = (select max(t2.create_date)
from dbo.translation_style_sheet t2
where t1.file_name = t2.file_name);
I'm trying to convert it to a hibernate criteria query, but haven't been able to figure it out. I'm assuming I need to use a DetachedCriteria to handle this, but not sure how to work with it.
This is what I have thus far.
DetachedCriteria maxCreateDate = DetachedCriteria.forClass(TranslationStyleSheet.class, "translationStyleSheet2")
.setProjection( Property.forName("createDate").max() )
.add( Property.forName("translationStyleSheet2.fileName").eqProperty("translationStyleSheet.fileName") );
List<TranslationStyleSheet> translationStyleSheets = this.session.createCriteria(TranslationStyleSheet.class, "translationStyleSheet")
.add( Property.forName("createDate").eq(maxCreateDate))
.list();
I'm getting the following exception.
org.hibernate.exception.GenericJDBCException
could not execute query
SQL
select this_.translation_style_sheet_id as translat1_20_0_, this_.create_date as create2_20_0_, this_.description as descript3_20_0_, this_.file_content as file4_20_0_, this_.file_extension as file5_20_0_, this_.file_name as file6_20_0_, this_.file_size as file7_20_0_, this_.style_sheet_content as style8_20_0_, this_.style_sheet_type as style9_20_0_ from translation_style_sheet this_ where this_.create_date = (select max(translationStyleSheet2_.create_date) as y0_ from translation_style_sheet translationStyleSheet2_ where translationStyleSheet2_.file_name=this_.file_name)
SQLState
ZZZZZ
Does anybody know what I'm doing wrong?
UPDATE
The error seems to be be happening at the max(translationStyleSheet2_.create_date) as y0_
as. When I remove the as y0_ in the sql statement, I'm able to run the query the query, however I'm not sure how to repair this in hibernate criteria though.

So I had no success getting this to work as a criteria query, but I did have success getting it to work as an HQL query.
HQL solution
this.session.createQuery("from TranslationStyleSheet this "
+ "where this.createDate = (select max(translationStyleSheet2.createDate) "
+ "from TranslationStyleSheet translationStyleSheet2 "
+ "where translationStyleSheet2.fileName=this.fileName)")
.list();
I'm still interested in getting the query to work as a criteria query though.

Related

CTE + INSERT INTO + SQLAlchemy

I am trying to insert some date into another table. At first I´ve tried to use sqlalchemy to create such queries, but as I got some error when executing, I tried to solve it through raw SQL, but the error still the same.
I am not very used to CTE commands, so I don´t know if there are some restrinctions over them.
WITH Conv_Pre_Pagos AS
(SELECT CONVENIO.COD_IDEN, CONVENIO.D_CLIENTE_NOM
FROM db2rpc.CONVENIO
WHERE CONVENIO.COD_ESPC = 52)
INSERT INTO DB2I023A.ANL_TARF_PAGAS_PREPAGO (convenio, convenente) SELECT CBR_TARF_REC.NR_DOC_SIS_OGM, Conv_Pre_Pagos.D_CLIENTE_NOM
FROM DB2TFA.CBR_TARF_REC JOIN Conv_Pre_Pagos ON CBR_TARF_REC.NR_DOC_SIS_OGM = Conv_Pre_Pagos.COD_IDEN
The sentence is bigger, but I removed some data to bring it cleaner. Still, the same error:
ibm_db_dbi::ProgrammingError: SQLNumResultCols failed: [IBM][CLI Driver][DB2] SQL0199N The use of the reserved word "INSERT" following "INSERT" is not valid.
Expected tokens may include: "(SELECT ,". SQLSTATE=42601 SQLCODE=-199
[SQL: WITH Conv_Pre_Pagos AS (SELECT CONVENIO.COD_IDEN, CONVENIO.D_CLIENTE_NOM
FROM db2rpc.CONVENIO WHERE CONVENIO.COD_ESPC = 52)
INSERT INTO DB2I023A.ANL_TARF_PAGAS_PREPAGO (convenio, convenente)
SELECT CBR_TARF_REC.NR_DOC_SIS_OGM, Conv_Pre_Pagos.D_CLIENTE_NOM
FROM DB2TFA.CBR_TARF_REC JOIN Conv_Pre_Pagos ON CBR_TARF_REC.NR_DOC_SIS_OGM = Conv_Pre_Pagos.COD_IDEN]
(Background on this error at: https://sqlalche.me/e/14/f405)"
Where does it see an "insert following insert"?
Try this:
INSERT INTO DB2I023A.ANL_TARF_PAGAS_PREPAGO (convenio, convenente)
WITH Conv_Pre_Pagos AS
(
SELECT CONVENIO.COD_IDEN, CONVENIO.D_CLIENTE_NOM
FROM db2rpc.CONVENIO
WHERE CONVENIO.COD_ESPC = 52
)
SELECT CBR_TARF_REC.NR_DOC_SIS_OGM, Conv_Pre_Pagos.D_CLIENTE_NOM
FROM DB2TFA.CBR_TARF_REC
JOIN Conv_Pre_Pagos ON CBR_TARF_REC.NR_DOC_SIS_OGM = Conv_Pre_Pagos.COD_IDEN

nested exception is java.sql.SQLException: Column 'createdBy' not found

String sql = "select *,T.createdBy_id,(select count(*) from subscription S where S.topic_id=T.id) as subscriptionCount,"+
"(select count(*) from resource R where R.topic_id=T.id) as topicCount from topic T "+
"WHERE T.createdBy_id=6";
If I execute same query on mySQL shell, it works fine.
I have been trying this since a long time.Help appreciated

Hibernate query for employee with date

This is my code.. Query working when i search with mysql query(find it in screenshot).But failed with hiberbate query.
EmployeeAttendanceMaster masterEmployeeFromRepository = masterEmployeeRepository.findById(employee, date);
if (masterEmployeeFromRepository == null) {
System.out.println("SignIn Successfully");
}else System.out.println("You are already Logged In");
masterEmployeeRepository:
#Query("select me from EmployeeAttendanceMaster me where me.employee = ?1 and Date(me.date) = ?2 order by me.date desc")
EmployeeAttendanceMaster findById(Employee employee,Date date);
mysql db screenshot in with same query
Data with same date there in db..So it shoudnot go through if condition.It should follow else condition.But as long as i tried this it prints "SignIn Successfully"
Thanks advance
You are using the Spring Data JPA #Query annotation (as discerned from the full data type you have provided in the comments to your question). The query you specify with #Query (select me from EmployeeAttendanceMaster me ...) must be a valid JPA Query Language (JPQL) statement. From what I know and remember, JPQL does not have a Date() function. So, your query is invalid because it contains Date(me.date) which refers to a non-existent JPQL Date() function, even if you can run it directly on MySQL.
You can change your query declaration to:
#Query(value = "select * from EmployeeAttendanceMaster where employee_id = ?1 and Date(date) = ?2 order by date desc", nativeQuery = true)
This will force the JPA provider (Hibernate in your case) to treat the query as a native SQL query and will be executed on the underlying database without any translation. You will lose database independence though.

"Operation must use an updatable query" error in MS Access

I am stuck with this update query:
UPDATE [table1] n SET n.kdo = IIf( n.old_kdo IN (SELECT u.id FROM [table2] u WHERE u.id_c<>0),"1","0")
it gives me "Operation must use an updatable query" error (I have all read/write permission).
I have tried bypass it by using:
UPDATE [table1] n SET n.kdo = IIf( n.old_kdo IN (DLookup("id", "table2", "id_c<>0")),"1","0")
it works, but sadly it return first match only.
Anyone have any idea how to make it right? Would be some join query better solution?
Try replacing your subquery by a dFirst(), dCount() or similar function, and extend your criteria accordingly:
UPDATE [table1] n SET n.kdo =
iif(dCount("*", "table2", "id_c<>0 and id = " & n.old_kdo) > 0 ,"1","0")
Access is tricky for joins in Update queries.

How to group by SqlFunction with VarArgsSQLFunction in NHibernate

I'm trying to implement the following SQL query with QueryOver:
SELECT [Time]/1000
FROM TableName
GROUP BY [Time]/1000
Here's my current attempt:
var result = session
.QueryOver<TableName>
.Select(Projections.GroupProperty(
Projections.SqlFunction(
new VarArgsSQLFunction("(", "/", ")"),
NHibernateUtil.Int64,
Projections.Property("Time")
Projections.Constant(1000))
))
.List<object>();
Unfortunately I get the following exception (GenericADOException):
could execute query
[ SELECT (this_.Time/#p0) as y0_ FROM [TableName] this_ GROUP BY (this_.Time/?) ]
And the inner exception:
Incorrect syntax near ?.
I can replace the "GroupProperty" with a "Sum" and it works. Any idea what's missing?
Update:
Apparently it's a bug in NHibernate. See also this question.
Why don't you just use Projections.SqlGroupProjection:
var result = session
.QueryOver<TableName>
.Select(Projections.SqlGroupProjection(
Time/1000 AS TimeValue",
"Time/1000",
new[]{"TimeValue"},
new[]{NHibernateUtil.Int32}))
.List<object>();