how to convert the query to hibernate query language? - mysql

how to write this query in hibernate query language
select * from preferred_space p, building b, floor f, space_type st, space s
where p.user_id=11
and p.space_id=s.id
and s.building_id=b.id
and s.floor_id=f.id
and s.space_type_id=st.id
order by p.id;
If I do it this way it is showing me an error?
String sql = "from PreferredSpace p, Space s, Building b, Floor f, SpaceType st " +
"where p.userId = ? " +
"and p.spaceId = s.id" +
"and s.buildingId = b.id" +
"and s.floorId = f.id" +
"and s.spaceTypeId = st.id" +
"order by p.id";
error:
ERROR o.h.hql.internal.ast.ErrorCounter - line 1:242: unexpected token: s
16:18:17.569 [http-bio-8080-exec-24] ERROR o.h.hql.internal.ast.ErrorCounter - line 1:242: unexpected token: s
antlr.NoViableAltException: unexpected token: s
shows the same error for every row that starts with "s." and also for "by".

You need to add spaces:
String sql = "from PreferredSpace p, Space s, Building b, Floor f, SpaceType st " +
"where p.userId = ? " +
"and p.spaceId = s.id " +
"and s.buildingId = b.id " +
"and s.floorId = f.id " +
"and s.spaceTypeId = st.id " +
"order by p.id";

Related

Mysql Query With Like Operator and order by keyword giving empty records in spring boot api

native Query I Wrote in My Repository
If i remove order by condition in the below query , it is giving some records but i want it in some order so i added order by condition then it not showing records only . but the same mysql query with order by condition is giving some records in mysql workbench.
#Query(value = "SELECT l.id AS id,l.first_name AS firstName,l.last_name AS lastName,"
+ " l.email AS email,l.phone AS phone,l.place AS place,l.course_id AS courseId,"
+ " c.name AS courseName,l.source AS source,l.enquiry_for AS enquiryFor,"
+ " l.appointment_date AS appointmentDate,l.description AS description,"
+ " l.discount AS discount,l.status AS status,l.assignee_id AS assigneeId,"
+ " ase.first_name AS assigneeFirstName,ase.last_name AS assigneeLastName,"
+ " l.assignor_id AS assignorId,asr.first_name AS assignorFirstName,"
+ " asr.last_name AS assignorLastName,l.active AS active,l.created_date AS createdDate,"
+ " l.updated_date AS updatedDate,(SELECT comments FROM reviews where created_date IN"
+ " (SELECT MAX(created_date) from reviews where lead_id=l.id)) AS latestComment FROM "
+ " leads l JOIN users AS ase ON l.assignee_id = ase.id JOIN users AS asr ON "
+ " l.assignor_id = asr.id JOIN courses AS c ON l.course_id =c.id WHERE l.status!='Draft'"
+ " AND (l.first_name LIKE '%:keyword%' OR l.last_name LIKE '%:keyword%' OR l.phone LIKE"
+ " '%:keyword%') ORDER BY -l.appointment_date DESC,l.created_date ASC", nativeQuery=true)
List<Leads> searchLeadsForAdmin(#Param("keyword") String searchKeyword);
i don't know Where am i going wrong , attached image below mysql query result came in workbench.
I found the answer to my question. It was a concatenation issue. In the second last line of my query after 'l.phone LIKE' I added the value in the next line.
+ " AND l.first_name LIKE %:keyword% OR l.last_name LIKE %:keyword% OR "
+ " l.phone LIKE %:keyword% ORDER BY -l.appointment_date DESC,"
+ " l.created_date ASC", nativeQuery = true)
The above query works.

unable to evaluate the expression method threw 'java.lang.illegalargumentexception' exception while excuting the flexible search query

hai i am getting products details from db while exceuting the flexiblesearchservice.search(query) it is throwing this error.my flexible search query is working fine with hac. but throwing error from flexible search service. my query and service is shown below.
"({{select {p:"+ProductModel.PK+"} from { "+ OrderModel._TYPECODE +" as o " +
" join "+ OrderStatus._TYPECODE+" as os on {os:pk} = {o:"+OrderModel.STATUS+"}"+
" join "+ OrderEntryModel._TYPECODE +" as oe on {oe:"+ OrderEntryModel.ORDER +"} = {o:"+OrderModel.PK+"}"+
" join "+ ProductModel._TYPECODE +" as p on {oe:"+OrderEntryModel.PRODUCT+"} = {p:"+ProductModel.PK+"}"+
" join "+ CatalogVersionModel._TYPECODE+" as cv on { p:"+ProductModel.CATALOGVERSION +"} = {cv:"+CatalogVersionModel.PK+"}"+
" join "+ CatalogModel._TYPECODE +" as c on {p:"+ProductModel.CATALOG+"} = {c:"+CatalogModel.PK+"}} "+
"where {os:code}='"+OrderStatus.COMPLETED +"' and {"+OrderModel.DATE+"}>'2017-08-16 00:00:00.000' " +
"and {"+OrderModel.DATE+"}<'2020-09-30 00:00:00.000' " +
"and {cv:"+CatalogVersionModel.VERSION+"}= 'Online' " +
"and {c:"+CatalogModel.ID+"} like 'apparelProductCatalog' " +
"group by {p:"+ProductModel.PK+"} order by sum({oe:"+OrderEntryModel.QUANTITY+"}) desc" +
" limit 10 }})";
final FlexibleSearchQuery fQuery = new FlexibleSearchQuery(QUERY);
fQuery.setResultClassList(Arrays.asList(ProductModel.class));
final SearchResult<ProductModel> searchResult =flexibleSearchService.search(fQuery);
final List<ProductModel> productModelList= searchResult.getResult();```
**error:** unable to evaluate the expression method threw 'java.lang.illegalargumentexception' exception
please help me out.
"where {os:code}='"+OrderStatus.COMPLETED +"'
This above code may be the issue, OrderStatus.COMPLETED returns an object, not String.
You can pass it as a query parameter.
"where {os:code} = '" + OrderStatus.COMPLETED.getCode() +"'

MySql Insert Into JDBC

I'm trying to execute a query using JDBC in mysql using INSERT INTO SELECT
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/new_db?&user=root&password=");
conn.setAutoCommit(false);
long start = System.currentTimeMillis();
String sql
= "INSERT INTO `tr_tmp`(`id`, `root_group_id`, `IATANO`, `NRPB`, `PlatedCarrierCode`, `PlatedCarrierName`, "
+ "`DateOfIssue`, `DomInt`, `FlownCarrierCode`, `FlownCarrierName`, `FlightNo`, `OperatedCarriercode`, "
+ "`FlightDate`, `Class`, `Origin`, `Destination`, `CashAmt`, `ExCashAmt`, `CreditAmt`, `EXCreditAmt`, "
+ "`EffCommAmt`, `EXEffCommAmt`, `RefCashAmt`, `RefCreditAmt`, `RefEffCommAmt`, "
+ "`ACMCashAmt`, `ACMCreditAmt`, `ACMEffCommAmt`, `ADMCashAmt`, `ADMCreditAmt`, `ADMEffCommAmt`, "
+ "`Farebasis`, `TaxCashAmt`, `EXTaxCashAmt`, "
+ "`TaxCreditAmt`, `EXTaxCreditAmt`, `RefTaxCashAmt`, `RefTaxCreditAmt`, "
+ "`ACMTaxCashAmt`, `ACMTaxCreditAmt`, `ADMTaxCashAmt`, `ADMTaxCreditAmt`, "
+ " `YQTax`, `EXYQtax`, `YRTax`, `EXYRtax`, `Currency`, NFCode) "
+ "(SELECT null, 100 as groupId, a.agtn as `IATANO`, b.nrid as NRPB, m.CarrierCode as PlatedCarrierCode, m.CarrierName as PlatedCarrierName, "
+ "c.DAIS as DateOfIssue, c.STAT as DomInt,j.CARR as FlownCarrierCode , l.CarrierName as FlownCarrierName, TRIM(LEADING '0' FROM j.FTNR) as FlightNo, j.OP_CARR as OP_CARR, "
+ "j.FLIGHTDT as FlightDate, j.RBKD as Class, j.ORAC AS Origin, j.DSTC AS Destination, k.CashAmt, k.ExCashAmt, k.CreditAmt, k.EXCreditAmt, "
+ "k.EffCommAmt as EffCommAmt,k.EXEffCommAmt as EXEffCommAmt, "
+ "k.RefCashAmt as RefCashAmt, k.RefCreditAmt as RefCreditAmt, k.RefEffCommAmt as RefEffCommAmt, "
+ "k.ACMCashAmt as ACMCashAmt, k.ACMCreditAmt as ACMCreditAmt, k.ACMEffCommAmt as ACMEffCommAmt, "
+ "k.ADMCashAmt as ADMCashAmt, k.ADMCreditAmt as ADMCreditAmt, k.ADMEffCommAmt as ADMEffCommAmt, "
+ "j.FBTD as Farebasis,k.TaxCashAmt as TaxCashAmt, k.EXTaxCashAmt as EXTaxCashAmt, "
+ "k.TaxCreditAmt, k.EXTaxCreditAmt, k.RefTaxCashAmt, k.RefTaxCreditAmt, "
+ "k.ACMTaxCashAmt, k.ACMTaxCreditAmt, k.ADMTaxCashAmt, k.ADMTaxCreditAmt, "
+ "k.YQTax, k.EXYQtax, k.YRTax, k.EXYRtax, k.CUTP as Currency, c.NefCode as NFCode "
+ "FROM tp_boh03 a "
+ "INNER JOIN tp_bkt06 b ON a.offheadid= b.offheadid "
+ "INNER JOIN tp_tickets c ON b.transheadid= c.transheadid "
+ "LEFT JOIN tp_bks39 f ON c.TicketHeadId = f.TicketHeadId "
+ "INNER JOIN tp_bki63 j ON c.TicketHeadId = j.TicketHeadId "
+ "INNER JOIN tp_mileage_fare k ON j.ItinerarySegmentID = k.ItinerarySegmentID "
+ "INNER JOIN tp_iata ti ON a.AGTN = ti.iata_no "
+ "LEFT JOIN tp_carriers l ON j.CARR = l.CarrierCode "
+ "LEFT JOIN tp_carriers m ON b.TACN = m.TicketCode)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.execute();
System.out.println("TIME TAKE : " + (System.currentTimeMillis() - start));
} catch (Exception ex) {
ex.printStackTrace();
}
The data expected should insert rows amounting to 2 million, but it's not inserting all data, every run of the script the rows being inserted changes. I tried to run the script directly in mysql and it did inserted same amount of rows after few re-runs.

Unexpected Token Exception in SQL Query in #Query() annotation in Spring

I am using a long SQL Query String inside #Query() annotation in Spring. I'm getting exceptions for multiple tokens. Can anybody provide the solution for the query below:
#Query("select p, top5.duration_seconds / 60 as duration_minutes, top5.max_seconds / 60 as max_minutes " +
"from (select r.driver_id, "+
"sum(to_seconds(r.end_time) - to_seconds(r.start_time)) as duration_seconds, "+
"max(to_seconds(r.end_time) - to_seconds(r.start_time)) as max_seconds "+
"from ride r "+
"where r.start_time >= '2018-08-08T12:12:12' and "+
"r.end_time <= '2018-08-08T18:12:12' "+
"group by r.driver_id "+
"order by duration_seconds desc "+
"limit 5 "+
") top5 join "+
"person p "+
"on top5.driver_id = p.id")
It shows
UnExpectedToken: sum
antlr.NoViableAltException: unexpected token: (
antlr.MismatchedTokenException: expecting EOF, found ')'

How to give extra parameter with HQL join

I would like to give extra parameter with join condition in hql.
In sql query I write
select a.*,ur.fname,ur.lname
from
atom as a
left join user as ur
on
a.id=ur.id
left join album as al
on
a.id=al.aid
and al.name='Profile'
left join post_images as pi
on
a.id=pi.aid
and pi.is_album_cover='yes'
where
(ur.fname like '%n%'
or ur.fname like '%n%')
and a.status='active';
which work propery and give desired result.
In hql I dont know how to give extra parameter with join
for fetching data I write(without extra parameter)
feeds = (List<Atom>) session.createQuery(
"select distinct atom from Atom as atom "
+ "left join fetch atom.albums as album "
+ "left join fetch album.postImageses as coverImage "
+ "left join fetch atom.user as user "
+ "where "
+ "(atom.user.fname like :name "
+ "or atom.user.lname like :name )"
+ "and album.name=:albumName "
+ "and coverImage.isAlbumCover=:isCover "
+ "and atom.status=:status ")
.setParameter("albumName", "Profile")
.setParameter("name", '%' + name + '%')
.setParameter("name", '%' + name + '%')
.setParameter("isCover", "yes")
.setParameter("status", "active")
.setFirstResult(0)
.setMaxResults(30)
.list();
Which is not giving any result how can I give extra parameter with join
In HQL, You may supply extra join conditions using the HQL with keyword.
Chech Associations and joins in HQL
Try this:
Your HQL::
select distinct atom
from Atom as atom
left join atom.albums as album with album.name= "Profile"
left join atom.postImageses as coverImage with coverImage.isAlbumCover="yes"
left join atom.user as user
where (user.fname like name or user.lname like name) and atom.status="active";
Your CODE::
feeds = (List<Atom>) session.createQuery(
"select distinct atom from Atom as atom "
+ "left join atom.albums as album with album.name=:albumName "
+ "left join atom.postImageses as coverImage with coverImage.isAlbumCover=:isCover "
+ "left join atom.user as user "
+ "where (user.fname like :name or user.lname like :name) "
+ "and atom.status=:status ")
.setParameter("albumName", "Profile")
.setParameter("name", '%' + name + '%')
.setParameter("isCover", "yes")
.setParameter("status", "active")
.setFirstResult(0)
.setMaxResults(30)
.list();