JPA Convert List<Tuple> to List<myClass> - jpa

I have the following Criteria API code which returns List.
I would like to convert this to List<myClass>
How can I do this?
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<ProductCatalogue> pc = cq.from(ProductCatalogue.class);
Root<ProductList> al = cq.from(ProductList.class);
.......
.......
.......
Predicate[] predicates = new Predicate[predicateList.size()];
predicateList.toArray(predicates);
criteriaQuery.where(predicates);
TypedQuery<Tuple> typedQuery = getEntityManager().cq(criteriaQuery);
List<Tuple> tuple = typedQuery.getResultList();
Ideally I would like to
List<Employee> emp = tuple
However the above resulted in incompatible type error, I do not know how could I cast this.

If you insist on using a tuple query you'll have to convert the instances manually.
If myClass is an entity you should use CriteriaQuery< myClass> as perissf suggested, otherwise you may use a "constructor expression" to create instances directly from a select, for example:
select new com...myClass(c.id, c.price) FROM ProductList c WHERE c.....;
See this answer for an example to create such a query using the Criteria API.

Related

JPA Specification subquery with AND doesn't work as expected

I'm having a weird issue, I need to connect a View (Workbench) with a table (FA_TICKET), to stablish this connection I use IN operator with subselect... This is going ok... But... When I try to add a new filter to it, it not resolves.
Subquery<Workbench> subFr = query.subquery(Workbench.class);
Root<FrTicket> rootFrTicket = subFr.from(FrTicket.class);
subFr.select(rootFrTicket.get("ticketId"));
Predicate pred = root.get("ticketNum").in(subFr);
criteriaBuilder.and(pred, criteriaBuilder.equal(root.get("type"), TicketType.FR_TICKET));
predicates.add(pred);
....
//predicates is defined at begining and have other filters
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
When I see the sub-query section, it should be like:
select .... from Workbench where ... and (ticketNum in (SUBSELECT) and type = ?)
But... The line about ticket type is never resolved and I see:
select .... from Workbench where ... and (ticketNum in (SUBSELECT))
If I change the order when define the and, I see this:
Predicate pred = criteriaBuilder.equal(root.get("type"), TicketType.FR_TICKET);
criteriaBuilder.and(pred, root.get("ticketNum").in(subFr));
select .... from Workbench where ... and (type = ?)
How I can include this type in the same group?
Because I need to stablish a filter with other kind of Ticket entities, with a different type.
Thanks
Looks like the problem apears with enums, they are problematic with CriteriaBuilder class.
So, if I make this change:
Subquery<Workbench> subFr = query.subquery(Workbench.class);
Root<FrTicket> rootFrTicket = subFr.from(FrTicket.class);
subFr.select(rootFrTicket.get("ticketId"));
Predicate pred = root.get("ticketNum").in(subFr);
criteriaBuilder.and(pred, criteriaBuilder.equal(root.get("type").as(String.class), TicketType.FR_TICKET).name());
predicates.add(pred);
....
//predicates is defined at begining and have other filters
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
Works smooth.

In C#, how do I get a distinct value from an IEnumerable using LINQ?

I have an IEnumerable variable that I want to extract a distinct value from. I know all the entries in the rows of the list have the same value, I just need to get that value.
The method returns an IEnumerable.
The row in the IEnumerable is defined as:
QuoteCovId
AdditionalInterestId
AdditionalInterestsAffiliateId
AdditionalInterestsLastName
AdditionalInterestsBusinessAddrLine1
AdditionalInterestsBusinessCity
AdditionalInterestsBusinessState
AdditionalInterestsBusinessZip
Sampel of code:
IadditionalInterestData = AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor);
// Using linq.
var quotes = from ai in IadditionalInterestData
select Distinct(ai.QuoteCovId);
// Iterate thru to get the 1 value.
foreach (int QuoteCovId in quotes)
{
quoteID = QuoteCovId;
}
var quoteId = AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor)
.FirstOrDefault().Select(f => f.QuoteCovId);
But that method:
AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor);
returns me an IEnumerable which I will use further in my application. Which is what I need.
So how will your suggestion still give me that IEnumerable and give me the quote value which happens to be the same in the collection?
var quoteId = AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor).FirstOrDefault().Select(f => f.QuoteCovId);
Also, I just added your line of code as is and I get an error statement.

How do we convert a column from table to an arraylist using ormlite?

I'm trying to convert an entire column values into a arrayList using ormlite on android, is this possible, with direct api?
Using raw results i get close, but not quite:
GenericRawResults<String[]> rawResults =
getHelper().getMyProcessDao().queryRaw(
queryBuild.selectColumns("nid").prepareStatementString());
List<String[]> result = rawResults.getResults();
Hrm. I'm not sure this is what you want. However, one way to accomplish what you ask for specifically is through by using the RawRowMapper which can be passed to ORMLite's DAO method: dao.queryRaw(String, Rowmapper, String...).
Something like the following should work:
RawRowMapper<Integer> mapper = new RawRowMapper<Integer>() {
public Integer mapRow(String[] columnNames, String[] resultColumns) {
// maybe you should verify that there _is_ only 1 column here
// maybe you should handle the possibility of a bad number and throw
return Integer.parseInt(resultColumns[0]);
}
};
GenericRawResults<Integer> rawResults =
getHelper().getMyProcessDao().queryRaw(
queryBuild.selectColumns("nid").prepareStatementString(), mapper);
List<Integer> list = rawResults.getResults();

Problem in LINQ query formation

I have written
List<int> Uids = new List<int>();
Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select new int
{
id = baseRecord.Id
}).ToList<int>();
Getting error: 'int' does not contain a definition for 'id'
what is the problem that i created?
Thanks
Try this:
List<int> Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select baseRecord.Id).ToList<int>();
Since you want to get a list of integers you can simply project the Id property from your query and then use the ToList extension method to buffer them into a List<T>. As a side note, are you certain that a List<T> is the right type to use here? You are forgoing the benefit of deferred execution and will not be able to stream these ids if you buffer them into a List<T>.
Your code is trying to instantiate ints, setting an id property that doesn't exist. I think the following is what you need.
Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select baseRecord.Id).ToList<int>();
The problem is with the: select new int {} part.
Try simply doing:
List<int> Uids = new List<int>();
Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select baseRecord.Id
)
.ToList<int>();
select new {} syntax is for defining anonymous types (where use is limited to the same function scope).
Andrew.

Linq to Entities and Xml Fields

I have this scenario:
A SQL Server table myTable with field1, xmlField (nvarchar(50) and xml sql server data type)
Linq to entities
Now I'd like to get a query like this:
SELECT Field1, XmlField
FROM MyTable
WHERE CAST(XmlField AS nvarchar(4000)) = '<myXml />'
Obviously this is a correct query in SQL Server but I can't find a solution to write this in L2E.
Please notify that this code doesn't work:
var query = from row in context.MyTables
where (string)row.XmlField == "<myXml />"
select row
and other cast methods too.
This just because in L2E the "ToString" does't work correctly.
Now my idea is this one: an extension method:
var query = from row in context.MyTables
select row
query = query.CompareXml("XmlField", "<myXml />")
and this is the extended method:
public static IQueryable<TSource> CompareXml<TSource>(this IQueryable<TSource> source, string xmlFieldName, string xmlToCompare)
{
ConstantExpression xmlValue = Expression.Constant(xmlToCompare);
ParameterExpression parameter = Expression.Parameter(typeof(TSource), source.ElementType.Name);
PropertyInfo propertyInfo = typeof(TSource).GetProperty(xmlFieldName);
MemberExpression memberAccess = Expression.MakeMemberAccess(parameter, propertyInfo);
var stringMember = Expression.Convert(memberAccess, typeof(string));
BinaryExpression clauseExpression = Expression.Equal(xmlValue, stringMember);
return source.Where(Expression.Lambda<Func<TSource, bool>>(clauseExpression, parameter));
}
and again this doesn't work too.
Now I'd like to understand how I can force a "Convert" using Cast so I can compare Xml and nvarchar.
Thanks in advance
Massimiliano
Unfortunately EF still doesn't properly support XML columns. I'm afraid pretty much the only choice I know of is to create a view that does the cast and map that to a different entity. This will probably make the code awkward but also offers additional possible scenarios; for example, with a lot of SQL code, you could map elements in the XML columns to actual columns in the view, allowing you to make queries on specific parts of the XML.
On the bright side, at least inserting values in an XML column works pretty much as expected.