Entity Framework - how to join tables without LINQ and with only string? - sql

I have a question about Entity Framework. Please answer if you know answer on this. I have such query :
String queryRaw =
"SELECT " +
"p.ProductName AS ProductName " +
"FROM ProductEntities.Products AS p " +
"INNER JOIN CategoryEntities.Categories AS c " +
"ON p.CategoryID = c.CategoryID ";
ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryRaw, entityContext);
GridView1.DataSource = query;
GridView1.DataBind();
Particularly I want to join few tables in one query, but I can NOT use LINQ and can NOT use ObjectQuery with objects mapped to DB fields inside my query. Because each entity creates dynamically. So this is what i can NOT use :
msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic12
msdn.microsoft.com/en-us/library/bb896339%28v=VS.90%29.aspx
The question is can I use something like this instead of using objects?
query.Join ("INNER JOIN CategoryEntities.Category ON p.CategoryID = c.CategoryID ");
The purpose is to use Join method of ObjectQuery with syntax as in Where method :
msdn.microsoft.com/en-us/library/bb338811%28v=VS.90%29.aspx
Thanks, Artem

Any decision i see right now is to temporary convert ObjectQuery to string, add joined table as string and then convert it back to ObjectQuery :
RoutesEntities routesModel = new RoutesEntities(entityConnection);
String queryRaw = "SELECT " +
"rs.RouteID AS RouteID, " +
"rs.LocaleID AS LocaleID, " +
"rs.IsSystem AS IsSystem " +
"FROM RoutesEntities.Routes AS rs ";
_queryData = new ObjectQuery<DbDataRecord>(queryRaw, routesModel);
var queryJoin = _queryData.CommandText + " INNER JOIN LocalesEntities.Locales AS ls ON ls.LocaleID = rs.LocaleID ";
_queryData = new ObjectQuery<DbDataRecord>(queryJoin, routesModel);
Maybe someone has more consistent suggestions?

Finally I Found a better solution for this, we can use Sub Query inside main Query. For example :
var db = CustomEntity();
ObjectQuery<Categories> query1 = db.Categories.Where("it.CategoryName='Demo'").Select ("it.CategoryID");
var categorySQL = query1.ToTraceString().Replace("dbo", "CustomEntity"); // E-SQL need this syntax
ObjectQuery<Products> query2 = db.Categories.Where("it.CategoryID = (" + categorySQL + ")");
Some example is here :
http://msdn.microsoft.com/en-us/library/bb896238.aspx
Good luck!

Related

How to write IN clause in hibernate native(createNative) query?

How to complete this query with IN clause?
ArrayList<Long> statusIds = new ArrayList<Long>();
_merchantTransaction.getMerchantTxnStatusList().forEach(statusItem ->{
statusIds.add(statusItem.getMerchantTxnStatusId());
});
Query query = entityManager.createNativeQuery("select *"
+ " from merchant_transactions mt"
+ " inner join appl_merchant_txn_statuses mts on mt.merchant_txn_status_id = mts.merchant_txn_status_id"
+ " where"
+ " mt.customer_id ="+ _merchantTransaction.getCustomerId()
+ " and mt.merchant_transaction_type_id = "+ _merchantTransaction.getMerchantTransactionType().getMerchantTransactionTypeId()
+ " and mt.merchant_txn_status_id in " + statusIds
,MerchantTransaction.class);
While executing, this result following query and it gives
SQLGrammerExecption.
select *
from merchant_transactions mt where
mt.customer_id = 3998
and mt.merchant_transaction_type_id = 2
and mt.merchant_txn_status_id in [1, 8]);
How to solve this?
Thanks & Regards,
Dasun.
You should consider using named parameter bindings instead of adding the parameters directly by concatenation as follows:
Query query =
entityManager.createNativeQuery("select *"
+ " from merchant_transactions mt"
+ " inner join appl_merchant_txn_statuses mts on mt.merchant_txn_status_id = mts.merchant_txn_status_id"
+ " where mt.customer_id = :customer_id"
+ " and mt.merchant_transaction_type_id = :merchant_transaction_type_id"
+ " and mt.merchant_txn_status_id in (:status_ids)", MerchantTransaction.class);
query.setParameter("customer_id", _merchantTransaction.getCustomerId());
query.setParameter("merchant_transaction_type_id", _merchantTransaction.getMerchantTransactionType().getMerchantTransactionTypeId());
query.setParameter("status_ids", statusIds);
Advantages of named parameter bindings as described in hibernate best-practices here:
you do not need to worry about SQL injection,
Hibernate maps your query parameters to the correct types and
Hibernate can do internal optimizations to provide better
performance.
As a side note, I see that you are using JPA's Entity Manager createNativeQuery, so this will work:
query.setParameter("status_ids", statusIds);
If you were using Hibernate createSQLQuery, you need this:
query.setParameterList("status_ids", statusIds);

Joining unrelated tables via JPQL

I have the following query which works. All the tables in this query have relations in some way.
#Repository(value = "ARepository")
public interface ARepository extends JpaRepository<CardEntity, String> {
#Query("SELECT xref.shortUtlTx FROM CardEntity card " +
"JOIN card.apexUrlCrossRef xref " +
"JOIN xref.sampleProdOffer offer " +
"WHERE xref.apexCard.cardNumber = :cardNum " +
"AND offer.apexeeOfferId = :myCode"
)
List<String> getAllValues(#Param("cardNum") String cardNum, #Param("myCode") String myCode);
}
But I also wish to join another table (Entity name -> UrlCountEntity) to this query but that table has no relation to the other tables in this query. Is there a way I could do this?
Based on reading a blog, I tried the following but throws errors.
Added this line to the query:
AND EXISTS (SELECT referCount FROM UrlCountEntity referCount WHERE
referCount.url.urlTx = xref.shortUtlTx)
#Repository(value = "ARepository")
public interface ARepository extends JpaRepository<CardEntity, String> {
#Query("SELECT xref.shortUtlTx FROM CardEntity card " +
"JOIN card.apexUrlCrossRef xref " +
"JOIN xref.sampleProdOffer offer " +
"WHERE xref.apexCard.cardNumber = :cardNum " +
"AND offer.apexeeOfferId = :myCode " +
"AND EXISTS (SELECT referCount FROM UrlCountEntity referCount WHERE referCount.url.urlTx = xref.shortUtlTx)"
)
List<String> getAllValues(#Param("cardNum") String cardNum, #Param("myCode") String myCode);
}
Error as follows:
Method threw
'org.springframework.dao.InvalidDataAccessResourceUsageException'
exception.
could not extract ResultSet; SQL [n/a]
Based on this article:
Using Hibernate 5.1 or newer you can join two unrelated tables via JQPL same way you would do it in SQL:
SELECT first
FROM First first JOIN
Second second ON first.property = second.property
WHERE first.property = :param
So you would need to change your query to something like this:
#Query("SELECT xref.shortUtlTx FROM CardEntity card " +
"JOIN card.apexUrlCrossRef xref " +
"JOIN xref.sampleProdOffer offer " +
"JOIN UrlCountEntity referCount ON referCount.url.urlTx = xref.shortUtlTx" +
"WHERE xref.apexCard.cardNumber = :cardNum " +
"AND offer.apexeeOfferId = :myCode")
List<String> getAllValues(#Param("cardNum") String cardNum, #Param("myCode") String myCode);

Casting error after jpa query on database

This query gives a array ob objects instead of giving me the Tracking object back.
In the log i see:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.quoka.qis.ads.web.tracking.Tracking
#NamedNativeQuery(
name = "Tracking.findByNo",
query = "select * " +
"from inet.TRACKING t " +
"where t.prditmNO = ?1"
)
TypedQuery<Tracking> q = em.createNamedQuery("Tracking.findByNo", Tracking.class);
q.setParameter(1, adno);
List<Tracking> list = q.getResultList();
return list.isEmpty()?null:list.get(0);
Thanks for you help.
You use a native query. You should use a JPA query.
#NamedQuery( name = "Tracking.findByNo",
query = "select t " +
"from Tracking t " +
"where t.prditmNO = ?1" )

Hibernate Query doesn't work as expected

Hi i have the following Query:
String hql = "UPDATE Raumreservierung as rr " +
"set VON = :begin " +
"where VON = :Von " +
"and Raum_ID IN (SELECT r.ID FROM Raum r " +
"inner join r.Panel as pl with pl.ID = " + clientId + "";
IQuery query = CurrentSession.CreateQuery(hql);
query.SetParameter("begin", DateTime.Now);
query.SetParameter("Von", v.Von);
int result = query.ExecuteUpdate();
The Query do an Update on "VON". That works fine, but the rest of the Query is not working. It seems that the rest of the query is not working. But did not get any Error.
With the rest of the Query i mean the following part of the query:
"and Raum_ID IN (SELECT r.ID FROM Raum r " +
"inner join r.Panel as pl with pl.ID = " + clientId + "";
Because it should happen only a Update on the column "VON" for example when "clientId" is "AT2"
But that part is not working. Because the update happens also on other clientId.
You forgot to close your parentheses.
(Also, you should use a parameter for clientId too)

Linq query returning value from another class

Just a quick question about LINQ, I want to use a value from the returned dataset to lookup a value and return this. The line I am struggling with is .ViewingNotes = New Viewing(pt.ProspectId).GetViewings().Columns(7).ToString(). Is this possible?
With BusinessLayerObjectManager.Context
Return (From p As [Property] In .PropertySet
Join pt As Prospect In .Prospects On pt.Property.propertyID Equals p.propertyID
Where (p.Development.DevelopmentID = devId)
Select New DevelopmentList With {
.Apartment = p.propertyApartment + " " + p.Development.Name,
.PropertyId = p.propertyID,
.Client = pt.Client.clientFirstname + " " + pt.Client.clientLastname,
.ClientId = pt.Client.ClientID,
.ProspectiveDate = pt.prospectiveDate,
.ProspectiveStatus = pt.prospectiveStatus,
.Agent = pt.Client.userID,
.ViewingNotes = New Viewing(pt.ProspectId).GetViewings().Columns(7).ToString(),
.PropertyStatus = ""
}).ToList()
End With
Thanks in advance.
I suspect not, when the compiler tries to convert the 'Viewing(pt.ProspectId).GetViewings().Columns(7).ToString()' bit to SQL it will get very confused. You would need to do it in 2 stages.
Do the first Linq-to-entity select first returning just pt.ProspectId, with the .ToList() intact. Then use the results to do some more linq, linq-to-linq if you like, where you can do the lookup using a lambda.