selecting records from tables using HQL Query..........# - hql

how to select records from multiple tables by using HQL Query..
Session session=dao.getSessionFactory().openSession();
Query query=session.createQuery("from b.Customer_name PurchaseDetailBean p,BookingBean b where p.Booking_Id=b.Booking_Id ");
System.out.println("dlkkdc"+query);
arg0.getPortletSession().setAttribute("query", query);
Query q1 = (Query) arg0.getPortletSession().getAttribute("query");
Gson gson = new Gson();
System.out.println("***" + gson.toJson(q1.list()));
arg0.getPortletSession().setAttribute("adminsales", gson.toJson(q1.list()));
System.out.println("iiiiiiiiiiiiiiiiiiiiiiii"+gson.toJson(q1.list()));
ITZ showing error::
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: p near line 1, column 41 [from b.Customer_name PurchaseDetailBean p,Com.bean.BookingBean b where p.Booking_Id=b.Booking_Id ]

Selected column must be appear before from
So, change your Query from
Query query=session.createQuery
("from b.Customer_name PurchaseDetailBean p,BookingBean b where p.Booking_Id=b.Booking_Id ");
to
Query query=session.createQuery
("b.Customer_name from PurchaseDetailBean p,BookingBean b where p.Booking_Id=b.Booking_Id ");

Related

Group by with count on multiple table in LINQ

Sql query to LINQ: Both are pasted over here, getting issue in LINQ - need suggestion:
select bm.MachineId,al.AlarmId,am.AlarmName, count(al.AlarmId)AlarmCount
from BatchMachineWise bm
join AlarmLog al on bm.MachineId = al.MachineId
join Alarm am on am.AlarmId = al.AlarmId
where bm.BatchId = 12476
group by bm.MachineId,al.AlarmId,am.AlarmName
GroupBy returns IGrouping<TKey,TElement> interface which has Key property which should be used to access fields used for grouping:
select new AlarmSummary
{
MachineId = gr.Key.MachineId,
AlarmId = gr.Key.AlarmId,
AlarmName = gr.Key.AlarmName
....
}

Pageable in spring for paging on List<Object> is not working

I have a list of object which contain 10000 records i am trying to split that records in each of 10,
But somehow it is not working.. can someone have a look
#Query("select a.applicantid,coalesce(to_char(a.createdon,'yyyy-MM-dd'),to_char(filing_date,'yyyy-MM-dd')) as dt1, \r\n" +
"coalesce(c.companyname,i.InstituteName,(u.firstname||' '||u.lastname),\r\n" +
"u.firstname) ,a.c_denomination,cc.crop_common_name,cs.crop_botanical_name,\r\n" +
"a.id,aps.status,a.cropid, \r\n" +
"(select mv.varietytype from VarietyType mv where mv.id= a.varirtytypeid),\r\n" +
"(select sv.subvarietytype from SubVarietyType sv,VarietyType mvr \r\n" +
" where a.subvarietytypeid = sv.id and mvr.id= sv.varietyid),a.formtype,mcg.crop_group \r\n" +
" from Applications a left join ApplicantRegistration ap on \r\n" +
" a.applicantid = ap.id left join CompanyRegistration c on ap.companyid = c.id \r\n" +
" left join InstitutionRegistration i on ap.institutionid = i.id \r\n" +
" left join Crops cc on a.cropid = cc.id left join CropSpecies cs \r\n" +
" on a.cropspeciesid =cs.id left join InternalUser u on ap.id = u.applicantid \r\n" +
" left join ApplicationStatus aps on a.application_current_status = aps.id "
+ "left join CropGroup mcg on cc.cropgroupid = mcg.id order by a.id desc")
List<Object[]> getapplication_adminview();
List<Object[]> admin_viewapplication=applicationrepository.getapplication_adminview();
int pageNumber = 0;
int size = 10;
Pageable pageable = PageRequest.of(pageNumber, size); // object of pageable
Page<Object> pages = new PageImpl(admin_viewapplication, pageable, admin_viewapplication.size());
List<Object> lpage = pages.getContent(); // here i am getting the lpage size as 10000 but as i enter pageable as of size 10 i am expecting 10 results only
where i am going wrong in this ?
if i am trying to add pagable object to query and run the code i will get the following error:
Cannot create TypedQuery for query with more than one return using requested result type [java.lang.Long]; nested exception is java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [java.lang.Long]
Page just represents one page of data . So page.getContent() only return all data in one page which is specified through constructor when you create this page instance . It has nothing to do with splitting the data in a page.
If you want to split a list , use Lists from Guava is the simplest way to go :
List<List<Object>> splittedList = Lists.partition(list, 10);
If you want to do pagination which split all the data stored in the database into different smaller pages , split it at the database level rather than getting the whole list to the memory to split which will be very inefficient when the entire list is large. See this for how to split it at the database level by declaring Pageable in the query method.
We can use PagedListHolder which can change the list in pages and we can than fetch a page by setting it's page size and page.
PagedListHolder<Object> page = new PagedListHolder(admin_viewapplicationpage);
page.setPageSize(50); // number of items per page
page.setPage(0); // set to first page
int totalPages = page.getPageCount(); // gives the totalpages according to the main list
List<Object> admin_viewapplication = page.getPageList(); // a List which represents the current page which is the sublist
the following tutorial helped me
-> https://www.baeldung.com/spring-data-jpa-query
At this point 4.3. Spring Data JPA Versions Prior to 2.0.4
VERY IMPORTANT to add \ n-- #pageable \ n
Without this I was wrong
Also the pagination setting must be without ordering
PageRequest paginaConf = new PageRequest ((param1 - 1)
, param2);
Finally to convert the Page <Object []>
Page <Object []> list = myQueryofRepo ();
List <XXXModel> lstReturn = myConversor (list.getContent ());
Page <XXXModel> ret = new PageImpl <XXXModel> (lstReturn, pageConf, param2);

C# Linq orderby only works for fields returned?

I want to do a Linq query that joins three tables, but only returns data from two of them (the third is only joined for ordering purposes). I'm trying to order by columns that aren't in the output of the produced query, but they seem to be ignored:
var records = from q in _pdxContext.Qualifier
join aql in _pdxContext.ApplicationQualifierLink on q.Id equals aql.QualifierId
join qt in _pdxContext.QualifierType on q.QualifierTypeId equals qt.Id
where SOME_LIST.Contains(aql.ApplicationId)
orderby aql.Sequence
select new Qualifier
{
Id = q.Id,
QualifierType = new QualifierType
{
Id = qt.Id, Value = qt.Value
}
};
return records.Distinct().ToList();
The output SQL from this does NOT have an ORDER BY clause.
If I change the orderby to read like so:
orderby q.Id
... then the output SQL has the order by clause.
Does Linq ignore orderby statements when the mentioned columns aren't used in the output (as appears to be the case here)? If so, how do I order by columns not in the output?
It seems this is an SQL limitation. The error from the SQL Server engine:
"ORDER BY items must appear in the select list if SELECT DISTINCT is specified."
So, as written, I can't do what I want to do.
I ended up using:
using (var cnn = new SqlConnection(_connectionString))
{
string sql = #"select
min(q.Id) Id, q.QualifierTypeId, q.QualifierTypeId, min(q.AcaId) AcaId,
q.QualifierTypeId Id, qt.Value
from
qdb.Qualifier q
inner join qdb.QualifierType qt on qt.Id = q.QualifierTypeId
inner join ApplicationQualifierLink l on l.QualifierId = q.id
where l.ApplicationId in (" + string.Join(",", applicationIds) + #")
group by q.Text, q.QualifierTypeId, qt.Value";
qualifiers = cnn.Query<Qualifier, QualifierType, Qualifier>(sql,
(qualifier, type) =>
{
qualifier.QualifierType = type; return qualifier;
}
).ToList();
}
Note: When you attempt to use order by and distinct as in my original clause, no error is given, entity framework silently discards the order by without any error.

Linq Query with multiple joins and multiple conditions

I am using Telerik Data Access to perform OR mapping.
I am trying to use Linq for performing a join query but not sure how to proceed correctly.
The original sql query is given by:
'SELECT O.OPS_LEG_ID, O.ATD_DATE, O.DEP_AIRPORT_ACT, O.ARR_AIRPORT_ACT, O.ATA_DATE, '+
'O.FL_LOG_ATD_DATE, O.FL_LOG_ATA_DATE, O.FL_LOG_DEP_AIRPORT, O.FL_LOG_ARR_AIRPORT, '+
'O.FL_NB, O.DESIGNATOR, O.FL_LOG_ID, O.FL_LOG_STATUS '+
'FROM CREW_ROT_ROLE CR, OPS_LEG O, CREW_ROLES R, CREW_PAIRING_CMP CP '+
'WHERE CR.ROLE_CDE = R.ROLE_CDE '+
'AND CR.CREW_ROTATION_ID = CP.CREW_ROTATION_ID '+
'AND CP.OPS_LEG_ID = O.OPS_LEG_ID '+
'AND CR.CREW_CDE = :CREW_CDE '+
'AND O.ATD_DATE >= :D_FROM '+
'AND O.ATD_DATE <= :D_TO '+
//'AND R.ROLE_TYPE = 0 '+
'ORDER BY O.ATD_DATE
The corresponding Entities have been generated from the SQL tables. I am now trying to build the equivalent Linq query, which does not seem to work:
var results = from opsLeg in dbContext.OPS_LEGs
from crewRotationRole in dbContext.CREW_ROT_ROLEs
from crewRole in dbContext.CREW_ROLEs
from crewPairingComponent in dbContext.CREW_PAIRING_CMPs
where crewRotationRole.ROLE_CDE == crewRole.ROLE_CDE
&& crewRotationRole.CREW_ROTATION_ID == crewPairingComponent.CREW_ROTATION_ID
&& crewPairingComponent.OPS_LEG_ID == opsLeg.OPS_LEG_ID
&& crewRotationRole.CREW_CDE == userId
select new { OpsLegId = opsLeg.OPS_LEG_ID,
Designator = opsLeg.DESIGNATOR,
FlightNumber = opsLeg.FL_NB
};
Trying the previous query, raises an exception:
"Identifier 'ROLE_CDE' is not a parameter or variable or field of
'FlightLogEntities.OPS_LEG'. If 'ROLE_CDE' is a property please add
the FieldAlias or Storage attribute to it or declare it as a field's
alias."
Not sure how to proceed. What would be the correct query using Linq joins? Thanks!
If you are using a ORM like Entity framework, then the conceptual model would be mix of classes, which would provide a object centric view of data.
So, you would be using the Linq on Objects and in that case you need not write queries for joins as we do in SQL for a database. Conceptual model would contain objects which would be having relationships using navigational properties, and to access navigational properties you can access them as a property of object.
For e.g if there are 2 tables in Database, Customer & Orders. Following SQL statement will return all Orders for Customer number 1:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
Where Customers.CustomerID = 1
If we use the EF to generate to generate the conceptual model from Database, we would get class for Customer and Order and Customer class would have a property of ICollection. So, if you need the same results as the SQL query above, you would do it in following way
var CustomerOne = context.Customers.Where(x => x.CustomerID == 1);
var ordersForCustomerOne = CustomerOne.Orders;
You can try something like
var k = from r in dataContext.Order_Details
join t in dataContext.Orders on r.OrderID equals t.OrderID
select r.OrderID ;

LINQ queries with many-to-many tables in Entity Data Model

I'm trying to use LINQ to query the following Entity Data Model
based on this db model
I'd like to be able to pull a list of products based on ProductFacets.FacetTypeId.
Normally, I'd use joins and this wouldn't be a problem but I don't quite understand how to query many-to-many tables under the Entity DataModel.
This is an example sql query:
select p.Name, pf.FacetTypeId from Products p
inner join ProductFacets pf on p.ProductId = pf.ProductId
where pf.FacetTypeId in(8, 12)
Presuming EF 4:
var facetIds = new [] { 8, 12 };
var q = from p in Context.Products
where p.FacetTypes.Any(f => facetIds.Contains(f.FacetTypeId))
select p;
In EF (assuming the mapping is done correctly), joins are hardly ever used; navigation properties are used instead.
Your original SQL returns a tuple with repeated Name entries. With LINQ, it's often easier
to "shape" the queries into non-tuple results.
The following should be the same as the SQL, only instead of returning (Name, FacetTypeId) pairs with repeated Names, it will return a type that has a Name and a sequence of FacetTypeIds:
var facetIds = new [] { 8, 12 };
var result = from p in db.Products
select new
{
p.Name,
FacetTypeIds = from pf in p.FacetTypes
where pf.FacetTypeId == 8 || pf.FacetTypeId == 12
select pf.FacetTypeId,
};

Resources