spring mvc hibernate performance issues - sql

We are working on a spring mvc project with hibernate.
When we execute the following code:
try {
HibernateTemplate ht = new HibernateTemplate(sf);
List<Route> r = ht.findByNamedParam("select r from Route r inner join r.carPoolers as carPooler where (( r.owner.id = :userid ) or ( carPooler.user.id = :userid )) AND r.id =:routeID", new String[]{"userid", "routeID"} , new Object[]{ u.getId() , id});
if (r.size() == 1) {
return r.get(0);
} else {
return null;
}
} catch (DataAccessException ex) {
LogFactory.getLog(RouteRepository.class).fatal(ex);
return null;
}
this is the result:
SELECT ROUTE0_.ID AS ID4_, ROUTE0_.ARRIVALTIME AS ARRIVALT2_4_,
ROUTE0_.CAR_ID AS CAR13_4_, ROUTE0_.DATE AS DATE4_,
ROUTE0_.DAYOFWEEK AS DAYOFWEEK4_, ROUTE0_.DEPARTURETIME AS
DEPARTUR5_4_, ROUTE0_.ENDDATE AS ENDDATE4_, ROUTE0_.MESSAGEID
AS MESSAGEID4_, ROUTE0_.OPENSEATS AS OPENSEATS4_,
ROUTE0_.OWNER_ID AS OWNER14_4_, ROUTE0_.ROUTECACHE_ID AS
ROUTECACHE11_4_, ROUTE0_.ROUTEOPTIMIZED AS ROUTEOPT9_4_,
ROUTE0_.START_ID AS START12_4_, ROUTE0_.STOP_ID AS STOP10_4_
FROM ROUTE ROUTE0_ INNER JOIN CARPOOLER CARPOOLERS1_ ON
ROUTE0_.ID=CARPOOLERS1_.ROUTEID
WHERE (route0_.owner_id=? or carpoolers1_.user_id=?) and route0_.id=?
SELECT CAR0_.ID AS ID5_3_, CAR0_.BRAND_ID AS BRAND8_5_3_, CAR0_.CARNAME
AS CARNAME5_3_, CAR0_.CARTYPE AS CARTYPE5_3_, CAR0_.IMAGEURL AS
IMAGEURL5_3_, CAR0_.PRICEKM AS PRICEKM5_3_, CAR0_.SEATS AS
SEATS5_3_, CAR0_.USER_ID AS USER7_5_3_, BRAND1_.ID AS ID6_0_,
BRAND1_.BRANDNAME AS BRANDNAME6_0_, USER2_.ID AS ID0_1_,
USER2_.EMAIL AS EMAIL0_1_, USER2_.FACEBOOKID AS FACEBOOKID0_1_,
USER2_.FIRSTNAME AS FIRSTNAME0_1_, USER2_.GENDER AS GENDER0_1_,
USER2_.IMAGEURL AS IMAGEURL0_1_, USER2_.LANGUAGE_ID AS
LANGUAGE12_0_1_, USER2_.LASTNAME AS LASTNAME0_1_,
USER2_.MOBILEPHONE AS MOBILEPH8_0_1_, USER2_.PASSWORD AS
PASSWORD0_1_, USER2_.SMOKER AS SMOKER0_1_, USER2_.TELEPHONE AS
TELEPHONE0_1_, LANGUAGE3_.ID AS ID9_2_, LANGUAGE3_.LANGUAGE AS
LANGUAGE9_2_, LANGUAGE3_.LANGUAGECODE AS LANGUAGE3_9_2_
FROM CAR CAR0_ LEFT OUTER JOIN BRAND BRAND1_ ON
CAR0_.BRAND_ID=BRAND1_.ID LEFT OUTER JOIN USER USER2_ ON
CAR0_.USER_ID=USER2_.ID LEFT OUTER JOIN LANGUAGE LANGUAGE3_ ON
USER2_.LANGUAGE_ID=LANGUAGE3_.ID
WHERE car0_.id=?
SELECT USER0_.ID AS ID0_1_, USER0_.EMAIL AS EMAIL0_1_,
USER0_.FACEBOOKID AS FACEBOOKID0_1_, USER0_.FIRSTNAME AS
FIRSTNAME0_1_, USER0_.GENDER AS GENDER0_1_, USER0_.IMAGEURL AS
IMAGEURL0_1_, USER0_.LANGUAGE_ID AS LANGUAGE12_0_1_,
USER0_.LASTNAME AS LASTNAME0_1_, USER0_.MOBILEPHONE AS
MOBILEPH8_0_1_, USER0_.PASSWORD AS PASSWORD0_1_, USER0_.SMOKER
AS SMOKER0_1_, USER0_.TELEPHONE AS TELEPHONE0_1_, LANGUAGE1_.ID
AS ID9_0_, LANGUAGE1_.LANGUAGE AS LANGUAGE9_0_,
LANGUAGE1_.LANGUAGECODE AS LANGUAGE3_9_0_
FROM USER USER0_ LEFT OUTER JOIN LANGUAGE LANGUAGE1_ ON
USER0_.LANGUAGE_ID=LANGUAGE1_.ID
WHERE user0_.id=?
SELECT ROUTECACHE0_.ID AS ID7_2_, ROUTECACHE0_.AANTALM AS AANTALM7_2_,
ROUTECACHE0_.AANTALMIN AS AANTALMIN7_2_, ROUTECACHE0_.ACTIVE AS
ACTIVE7_2_, ROUTECACHE0_.JSON AS JSON7_2_,
ROUTECACHE0_.LOCATIONS AS LOCATIONS7_2_,
ROUTECACHE0_.LOCATIONSOPTIMIZED AS LOCATION7_7_2_,
ROUTECACHE0_.ROUTEOPTIMIZED AS ROUTEOPT8_7_2_,
ROUTECACHE0_.START_ID AS START10_7_2_, ROUTECACHE0_.STOP_ID AS
STOP9_7_2_, LOCATION1_.ID AS ID2_0_, LOCATION1_.LANG AS
LANG2_0_, LOCATION1_.LAT AS LAT2_0_, LOCATION1_.NUMBER AS
NUMBER2_0_, LOCATION1_.STREET AS STREET2_0_, LOCATION1_.ZIPCODE
AS ZIPCODE2_0_, LOCATION2_.ID AS ID2_1_, LOCATION2_.LANG AS
LANG2_1_, LOCATION2_.LAT AS LAT2_1_, LOCATION2_.NUMBER AS
NUMBER2_1_, LOCATION2_.STREET AS STREET2_1_, LOCATION2_.ZIPCODE
AS ZIPCODE2_1_
FROM ROUTECACHE ROUTECACHE0_ LEFT OUTER JOIN LOCATION LOCATION1_ ON
ROUTECACHE0_.START_ID=LOCATION1_.ID LEFT OUTER JOIN LOCATION
LOCATION2_ ON ROUTECACHE0_.STOP_ID=LOCATION2_.ID
WHERE routecache0_.id=?
SELECT ROUTECACHE0_.ROUTECACHESPUNTENTUSSEN_ID AS ROUTECAC1_1_,
ROUTECACHE0_.ROUTECACHETUSSENPUNTEN_ID AS ROUTECAC2_1_,
LOCATION1_.ID AS ID2_0_, LOCATION1_.LANG AS LANG2_0_,
LOCATION1_.LAT AS LAT2_0_, LOCATION1_.NUMBER AS NUMBER2_0_,
LOCATION1_.STREET AS STREET2_0_, LOCATION1_.ZIPCODE AS
ZIPCODE2_0_
FROM ROUTECACHE_LOCATION_PUNTEN ROUTECACHE0_ LEFT OUTER JOIN LOCATION
LOCATION1_ ON
ROUTECACHE0_.ROUTECACHETUSSENPUNTEN_ID=LOCATION1_.ID
WHERE routecache0_.routecachesPuntenTussen_id=?
SELECT CARPOOLERS0_.ROUTEID AS ROUTEID5_, CARPOOLERS0_.ID AS ID5_,
CARPOOLERS0_.ID AS ID3_4_, CARPOOLERS0_.APPROVED AS
APPROVED3_4_, CARPOOLERS0_.ONETIME AS ONETIME3_4_,
CARPOOLERS0_.ROUTEID AS ROUTEID3_4_, CARPOOLERS0_.START_ID AS
START5_3_4_, CARPOOLERS0_.STOP_ID AS STOP7_3_4_,
CARPOOLERS0_.USER_ID AS USER6_3_4_, LOCATION1_.ID AS ID2_0_,
LOCATION1_.LANG AS LANG2_0_, LOCATION1_.LAT AS LAT2_0_,
LOCATION1_.NUMBER AS NUMBER2_0_, LOCATION1_.STREET AS
STREET2_0_, LOCATION1_.ZIPCODE AS ZIPCODE2_0_, LOCATION2_.ID AS
ID2_1_, LOCATION2_.LANG AS LANG2_1_, LOCATION2_.LAT AS LAT2_1_,
LOCATION2_.NUMBER AS NUMBER2_1_, LOCATION2_.STREET AS
STREET2_1_, LOCATION2_.ZIPCODE AS ZIPCODE2_1_, USER3_.ID AS
ID0_2_, USER3_.EMAIL AS EMAIL0_2_, USER3_.FACEBOOKID AS
FACEBOOKID0_2_, USER3_.FIRSTNAME AS FIRSTNAME0_2_,
USER3_.GENDER AS GENDER0_2_, USER3_.IMAGEURL AS IMAGEURL0_2_,
USER3_.LANGUAGE_ID AS LANGUAGE12_0_2_, USER3_.LASTNAME AS
LASTNAME0_2_, USER3_.MOBILEPHONE AS MOBILEPH8_0_2_,
USER3_.PASSWORD AS PASSWORD0_2_, USER3_.SMOKER AS SMOKER0_2_,
USER3_.TELEPHONE AS TELEPHONE0_2_, LANGUAGE4_.ID AS ID9_3_,
LANGUAGE4_.LANGUAGE AS LANGUAGE9_3_, LANGUAGE4_.LANGUAGECODE AS
LANGUAGE3_9_3_
FROM CARPOOLER CARPOOLERS0_ LEFT OUTER JOIN LOCATION LOCATION1_ ON
CARPOOLERS0_.START_ID=LOCATION1_.ID LEFT OUTER JOIN LOCATION
LOCATION2_ ON CARPOOLERS0_.STOP_ID=LOCATION2_.ID LEFT OUTER
JOIN USER USER3_ ON CARPOOLERS0_.USER_ID=USER3_.ID LEFT OUTER
JOIN LANGUAGE LANGUAGE4_ ON USER3_.LANGUAGE_ID=LANGUAGE4_.ID
WHERE carpoolers0_.RouteId=?
Problem:
This takes minimum 460ms.
We only need the first query for our results.
,
ty in advance

You probably have so many queries because some relationships are eager loaded. Note that by default all OneToOne and ManyToOne relationships are eager loaded. This means that if a route has a car, which has a user, which has a language, etc., Hibernate will load all these referenced entities each time it loads a route.
Make them lazy loaded instead, and tune your queries to fetch only the entities you need.

I guess returned object is passed to some automatic serializer (you use #ResponseBody, yes?) that tries to serialize the whole graph of accessible objects and therefore triggers lazy loading of related objects which you don't need.
If so, you can create a DTO that contains only necessary fields, populate it from the loaded entity and return that DTO instead of entity.
Alternative approach would be to configure serializer to make it serialize only necessary fields, but it can be more complex.

See this for how to get only 1 result: How do you do a limit query in HQL?.
Have you configured indexes on your tables?

Related

Is there any way to use raw sql or i'm stuck with laravel-eloquent?

I'm trying to migrate an application developed in 2007 and add and api to it so I can easy develop and sync data with the new App I started a laravel project with the old database just to create the api the old database diagram look like this: Too many relationships and crazy polymorphic ones at that.
I want to migrate my query to laravel eloquent but I couldn't do it in time I tried to do it with eloquent but it took too much time is there any way to use raw sql like this or i'm stuck with eloquent this is my laravel code : here
the sql query looks like this
SELECT n.DOC_ID, n.TYP_ID, n.TYP_ID,
type_document.TYP_LIBELLE_AR, n.IND_ID,indication.IND_LIBELLE_AR,n.LAN_ID,
langue.LAN_LIBELLE_AR,
n.DOC_TITRE_PROPRE,
n.DOC_TITRE_COMPLEMENT,
n.DOC_TITRE_PARALLELE,
n.DOC_TITRE_ENSEMBLE,
n.DOC_NUMERO_PARTIE,
editeur.EDT_NOM_AR,
editeur.EDT_KEYWORDS,
n.DOC_LIEU_EDITION,
n.DOC_ANNEE,
n.DOC_EDITION,
periodicite.PER_LIBELLE_AR,
n.DIP_ID,
specialite.SPE_LIBELLE_AR,
n.COL_ID,
n.DOC_NUM,
n.COL_NUMERO,
n.COT_NOTICE,
n.SCL_ID,
n.SCL_NUMERO,
n.DOC_NBR_UNITE,
n.DOC_ILLUSTRATION,
n.DOC_FORMAT,
n.DOC_MATERIEL,
n.DOC_ISBN,
n.DOC_ISSN,
n.DOC_NBR_EXEMPLAIRE,
n.STA_ID,
n.REL_VOLUME,
n.PAY_ID,
n.DOC_AGENCE,
n.DOC_PRET_INTERNE,
n.DOC_PRET_EXTERNE,
n.DOC_KEYWORDS,
n.CREATE_DATE,
n.UPDATE_DATE,
statut_notice.STA_LIBELLE_AR,
notice_auteur.VED_ID,
notice_auteur.FON_ID,
notice_auteur.AUT_TYPE,
GROUP_CONCAT(DISTINCT vmath.VED_NOM) AS mats,
vmath.VED_KEYWORDS,
GROUP_CONCAT( DISTINCT vauth.VED_NOM) AS auths,
vauth.VED_KEYWORDS,
GROUP_CONCAT( DISTINCT notice_exemplaire.EXP_COTE) AS examp_cote,
GROUP_CONCAT( DISTINCT notice_exemplaire.LOC_ID) AS exmp_location
FROM notice n
INNER JOIN editeur ON editeur.EDT_ID =n.EDT_ID
INNER JOIN type_document ON type_document.TYP_ID = n.TYP_ID
INNER JOIN langue ON langue.LAN_ID = n.LAN_ID
INNER JOIN statut_notice ON statut_notice.STA_ID = n.STA_ID
INNER JOIN indication ON indication.IND_ID = n.IND_ID
INNER JOIN notice_exemplaire ON n.DOC_ID = notice_exemplaire.DOC_ID
LEFT JOIN specialite ON n.SPE_ID = specialite.SPE_ID
LEFT JOIN periodicite ON periodicite.PER_ID = n.PER_ID
INNER JOIN notice_auteur ON n.DOC_ID = notice_auteur.DOC_ID
INNER JOIN vedette vauth ON notice_auteur.VED_ID = vauth.VED_ID
LEFT JOIN notice_matiere ON n.DOC_ID = notice_matiere.DOC_ID
LEFT JOIN vedette vmath ON notice_matiere.VED_ID = vmath.VED_ID
GROUP BY n.DOC_ID
1:
For something like this you can use DB::select('YOUR-QUERY').
DB::select('...') calls select() on the underlying Connection class so it's not the same as using DB::table('...')->select('...') which is calling the select method on the Builder class.
For more information on running raw queries you can refer to the documentation.

Ignore null values in select statement

I'm trying to retrieve a list of components via my computer_system, BUT if a computer system's graphics card is set to null (I.e. It has an onboard), the row isn't returned by my select statement.
I've been trying to use COALESCE without results. I've also tried with and OR in my WHERE clause, which then just returns my computer system with all different kinds of graphic cards.
Relevant code:
SELECT
computer_system.cs_id,
computer_system.cs_name,
motherboard.name,
motherboard.price,
cpu.name,
cpu.price,
gfx.name,
gfx.price
FROM
public.computer_case ,
public.computer_system,
public.cpu,
public.gfx,
public.motherboard,
public.ram
WHERE
computer_system.cs_ram = ram.ram_id AND
computer_system.cs_cpu = cpu.cpu_id AND
computer_system.cs_mb = motherboard.mb_id AND
computer_system.cs_case = computer_case.case_id AND
computer_system.cs_gfx = gfx.gfx_id; <-- ( OR computer_system.cs_gfx IS NULL)
Returns:
1;"Computer1";"Fractal Design"; 721.00; "MSI Z87"; 982.00; "Core i7 I7-4770K "; 2147.00; "Crucial Gamer"; 1253.00; "ASUS GTX780";3328.00
Should I use Joins? Is there no easy way to say return the requested row, even if there's a bloody NULL value. Been struggling with this for at least 2 hours.
Tables will be posted if needed.
EDIT: It should return a second row:
2;"Computer2";"Fractal Design"; 721.00; "MSI Z87"; 982.00; "Core i7 I7-4770K "; 2147.00; "Crucial Gamer"; 1253.00; "null/nothing";null/nothing
You want a LEFT OUTER JOIN.
First, clean up your code so you use ANSI joins so it's readable:
SELECT
computer_system.cs_id,
computer_system.cs_name,
motherboard.name,
motherboard.price,
cpu.name,
cpu.price,
gfx.name,
gfx.price
FROM
public.computer_system
INNER JOIN public.computer_case ON computer_system.cs_case = computer_case.case_id
INNER JOIN public.cpu ON computer_system.cs_cpu = cpu.cpu_id
INNER JOIN public.gfx ON computer_system.cs_gfx = gfx.gfx_id
INNER JOIN public.motherboard ON computer_system.cs_mb = motherboard.mb_id
INNER JOIN public.ram ON computer_system.cs_ram = ram.ram_id;
Then change the INNER JOIN on public.gfx to a LEFT OUTER JOIN:
LEFT OUTER JOIN public.gfx ON computer_system.cs_gfx = gfx.gfx_id
See PostgreSQL tutorial - joins.
I very strongly recommend reading an introductory tutorial to SQL - at least the PostgreSQL tutorial, preferably some more material as well.
It looks like it's just a bracket placement issue. Pull the null check and the graphics card id comparison into a clause by itself.
...
computer_system.cs_case = computer_case.case_id AND
(computer_system.cs_gfx IS NULL OR computer_system.cs_gfx = gfx.gfx_id)
Additionally, you ask if you should use joins. You are in fact using joins, by virtue of having multiple tables in your FROM clause and specifying the join criteria in the WHERE clause. Changing this to use the JOIN ON syntax might be a little easier to read:
FROM sometable A
JOIN someothertable B
ON A.somefield = B.somefield
JOIN somethirdtable C
ON A.somefield = C.somefield
etc
Edit:
You also likely want to make the join where you expect the null value to be a left outer join:
SELECT * FROM
first_table a
LEFT OUTER JOIN second_table b
ON a.someValue = b.someValue
If there is no match in the join, the row from the left side will still be returned.

Need help optimizing this tSQL Query

I'm definitely not a DBA and unfortunately we don't have a DBA to consult within at our company. I was wondering if someone could give me a recommendation on how to improve this query, either by changing the query itself or adding indexes to the database.
Looking at the execution plan of the query it seems like the outer joins are killing the query. This query only returns 350k results, but it takes almost 30 seconds to complete. I don't know much about DB's, but I don't think this is good? Perhaps I'm wrong?
Any suggestions would be greatly appreciated. Thanks in advance.
As a side note this is obviously being create by an ORM and not me directly. We are using Linq-to-SQL.
SELECT
[t12].[value] AS [DiscoveryEnabled],
[t12].[value2] AS [isConnected],
[t12].[Interface],
[t12].[Description] AS [InterfaceDescription],
[t12].[value3] AS [Duplex],
[t12].[value4] AS [IsEnabled],
[t12].[value5] AS [Host],
[t12].[value6] AS [HostIP],
[t12].[value7] AS [MAC],
[t12].[value8] AS [MACadded],
[t12].[value9] AS [PortFast],
[t12].[value10] AS [PortSecurity],
[t12].[value11] AS [ShortHost],
[t12].[value12] AS [SNMPlink],
[t12].[value13] AS [Speed],
[t12].[value14] AS [InterfaceStatus],
[t12].[InterfaceType],
[t12].[value15] AS [IsUserPort],
[t12].[value16] AS [VLAN],
[t12].[value17] AS [Code],
[t12].[Description2] AS [Description],
[t12].[Host] AS [DeviceName],
[t12].[NET_OUID],
[t12].[DisplayName] AS [Net_OU],
[t12].[Enclave]
FROM (
SELECT
[t1].[DiscoveryEnabled] AS [value],
[t1].[IsConnected] AS [value2],
[t0].[Interface],
[t0].[Description],
[t2].[Duplex] AS [value3],
[t0].[IsEnabled] AS [value4],
[t3].[Host] AS [value5],
[t6].[Address] AS [value6],
[t3].[MAC] AS [value7],
[t3].[MACadded] AS [value8],
[t2].[PortFast] AS [value9],
[t2].[PortSecurity] AS [value10],
[t4].[Host] AS [value11],
[t0].[SNMPlink] AS [value12],
[t2].[Speed] AS [value13],
[t2].[InterfaceStatus] AS [value14],
[t8].[InterfaceType],
[t0].[IsUserPort] AS [value15],
[t2].[VLAN] AS [value16],
[t9].[Code] AS [value17],
[t9].[Description] AS [Description2],
[t7].[Host], [t7].[NET_OUID],
[t10].[DisplayName],
[t11].[Enclave],
[t7].[Decommissioned]
FROM [dbo].[IDB_Interface] AS [t0]
LEFT OUTER JOIN [dbo].[IDB_InterfaceLayer2] AS [t1] ON [t0].[IDB_Interface_ID] = [t1].[IDB_Interface_ID]
LEFT OUTER JOIN [dbo].[IDB_LANinterface] AS [t2] ON [t1].[IDB_InterfaceLayer2_ID] = [t2].[IDB_InterfaceLayer2_ID]
LEFT OUTER JOIN [dbo].[IDB_Host] AS [t3] ON [t2].[IDB_LANinterface_ID] = [t3].[IDB_LANinterface_ID]
LEFT OUTER JOIN [dbo].[IDB_Infrastructure] AS [t4] ON [t0].[IDB_Interface_ID] = [t4].[IDB_Interface_ID]
LEFT OUTER JOIN [dbo].[IDB_AddressMapIPv4] AS [t5] ON [t3].[IDB_AddressMapIPv4_ID] = ([t5].[IDB_AddressMapIPv4_ID])
LEFT OUTER JOIN [dbo].[IDB_AddressIPv4] AS [t6] ON [t5].[IDB_AddressIPv4_ID] = [t6].[IDB_AddressIPv4_ID]
INNER JOIN [dbo].[ART_Asset] AS [t7] ON [t7].[ART_Asset_ID] = [t0].[ART_Asset_ID]
LEFT OUTER JOIN [dbo].[NSD_InterfaceType] AS [t8] ON [t8].[NSD_InterfaceTypeID] = [t0].[NSD_InterfaceTypeID]
INNER JOIN [dbo].[NSD_InterfaceCode] AS [t9] ON [t9].[NSD_InterfaceCodeID] = [t0].[NSD_InterfaceCodeID]
INNER JOIN [dbo].[NET_OU] AS [t10] ON [t10].[NET_OUID] = [t7].[NET_OUID]
INNER JOIN [dbo].[NET_Enclave] AS [t11] ON [t11].[NET_EnclaveID] = [t10].[NET_EnclaveID]
) AS [t12]
WHERE ([t12].[Enclave] = 'USMC') AND (NOT ([t12].[Decommissioned] = 1))
LINQ-TO-SQL Query:
return from t in db.IDB_Interfaces
join v in db.IDB_InterfaceLayer3s on t.IDB_Interface_ID equals v.IDB_Interface_ID
join u in db.ART_Assets on t.ART_Asset_ID equals u.ART_Asset_ID
join c in db.NET_OUs on u.NET_OUID equals c.NET_OUID
join w in
(from d in db.IDB_InterfaceIPv4s
select new { d.IDB_InterfaceIPv4_ID, d.IDB_InterfaceLayer3_ID, d.IDB_AddressMapIPv4_ID, d.IDB_AddressMapIPv4.IDB_AddressIPv4.Address })
on v.IDB_InterfaceLayer3_ID equals w.IDB_InterfaceLayer3_ID
join h in db.NET_Enclaves on c.NET_EnclaveID equals h.NET_EnclaveID into enclaveLeftJoin
from i in enclaveLeftJoin.DefaultIfEmpty()
join m in
(from z in db.IDB_StandbyIPv4s
select new
{
z.IDB_InterfaceIPv4_ID,
z.IDB_AddressMapIPv4_ID,
z.IDB_AddressMapIPv4.IDB_AddressIPv4.Address,
z.Preempt,
z.Priority
})
on w.IDB_InterfaceIPv4_ID equals m.IDB_InterfaceIPv4_ID into standbyLeftJoin
from k in standbyLeftJoin.DefaultIfEmpty()
where t.ART_Asset.Decommissioned == false
select new NetIDBGridDataResults
{
DeviceName = u.Host,
Host = u.Host,
Interface = t.Interface,
IPAddress = w.Address,
ACLIn = v.InboundACL,
ACLOut = v.OutboundACL,
VirtualAddress = k.Address,
VirtualPriority = k.Priority,
VirtualPreempt = k.Preempt,
InterfaceDescription = t.Description,
Enclave = i.Enclave
};
As a rule (and this is very general), you want an index on:
JOIN fields (both sides)
Common WHERE filter fields
Possibly fields you aggregate
For this query, start with checking your JOIN criteria. Any one of those missing will force a table scan which is a big hit.
Looking at the execution plan of the query it seems like the outer joins are killing the query.
This query only returns 350k results, but it takes almost 30 seconds to complete. I don't know
much about DB's, but I don't think this is good? Perhaps I'm wrong?
A man has got to do waht a mana has got to do.
The joins may kill you, but when you need them YOU NEED THEM. Some tasks take long.
Make sure you ahve all indices you need.
Make sure your sql server is not a sad joke hardware wise.
All you can do.
I woudl bet someone has no clue about SQL and needs to be enlighted to the power of indices.

Nhibernate join filtering

I have a question about joins in NHIBERNATE. We had an issue with our sql query that was generated but nhibernate. Our db developer optimized the raw sql so it works as we need, but we need to change the nhibernate code to make generated sql look like optimized.
the part of the original part of the query is:
FROM PERSON_VISIT this_
inner join PERSON_Basic per2_
on this_.PERSON_ID = per2_.PERSON_ID
left outer join PERSONC_QUESTIONS perint10_
on per2_.PERSON_ID = perint10_.PERSON_ID
left outer join TELEPHONE_QUESTIONS intaudit13_
on perint10_.PP_QUESTIONS_ID = intaudit13_.PP_QUESTIONS_ID
inner join C_QUESTIONS intdef14_
on perint10_.QUESTION_ID = intdef14_.QUESTION_ID
and perint10_.QUESTIONS_CODE = intdef14_.QUESTIONS_CODE
and perint10_.QUESTION_ID = intdef14_.QUESTION_ID
The optimized one is :
FROM PERSON_VISIT this_
inner join PERSON_Basic per2_
on this_.PERSON_ID = per2_.PERSON_ID
left outer join PERSONC_QUESTIONS perint10_
on per2_.PERSON_ID = perint10_.PERSON_ID
left outer join TELEPHONE_QUESTIONS intaudit13_
on perint10_.PP_QUESTIONS_ID = intaudit13_.PP_QUESTIONS_ID
left outer join C_QUESTIONS intdef14_
on perint10_.QUESTION_ID = intdef14_.QUESTION_ID
and perint10_.QUESTIONS_CODE = intdef14_.QUESTIONS_CODE
and perint10_.QUESTION_ID = intdef14_.QUESTION_ID
and intdef14_.DISCIPLINE_CODE = this_.DISCIPLINE_CODE
To change query from inner join to left outer join is easy, i changed only one line of code:
.CreateAlias("PersonInt.QuestionEntity", "IntDef", JoinType.LeftOuterJoin)
But how I can add
and intdef14_.DISCIPLINE_CODE = this_.DISCIPLINE_CODE
using nhibernate code?
There is an option to add reference from PERSON_VISIT definition to C_QUESTIONS, but the problem is that
PERSON_VISIT is used everywhere and I don't want this change to possibly break other queries, I just wnat to add only one line of code to add, how I can do that? Is there any way to have access to the raw join to change it? Or some other way to add this
and intdef14_.DISCIPLINE_CODE = this_.DISCIPLINE_CODE
To the query?
I know that somebody will say that we can add a restriction to the query through criteria.Add, but it is not an option cause db developer optimized our query taking this restriction from WHERE clause to the join.
How I can do that quickly without changing the models definitions? Just changing only this one query without changing the whole model?
It is possible using HQL and the Criteria API's.
This question gives you the answer: Adding conditionals to outer joins with nhibernate
Something like this may solve your issue.
.CreateAlias("PersonInt.QuestionEntity", "IntDef", JoinType.LeftOuterJoin,
Restrictions.EqProperty("DISCIPLINE_CODE", "IntDef.DISCIPLINE_CODE"))
Thanks for answers. We use 2.0 version of NHibernate in our project so we didn't have a chance to use new methods of .CreateAlias with restrictions.
I have fixed an issue using Interceptors:
public class SqlInterceptor : EmptyInterceptor, IInterceptor
{
SqlString IInterceptor.OnPrepareStatement(SqlString sql)
{
//manipulating with the sql
return sql;
}
}
than
var factory = Session.SessionFactory;
var session = factory.OpenSession(new SqlInterceptor());
And use my query without a change.

NHibernate Left Outer Join Unrelated Entities

I have 2 entities Role & Translation.
Role -> Role_ID, Code
Translation -> Code, Language, Name
The idea is to say for a certain role, that it has English name, French name and so on.
For example:
A Role(1, 'Rol_001') can have the relations: Translation('Rol_001', 'English', '') & Translation('Rol_001', 'French', '').
I would like to express the following SQL query in HQL:
select r.Role_ID, t.Name
from Role r left outer join Translation t
on r.Code = t.Code and t.Language = #lang;
In my mapping files I don't have any relation between the 2 entities but the following HQL query works as if it is inner join
IQuery query = session.CreateQuery("select new Lookup(r.Role, t.Name) from Role r, Translation t where r.Code = r.Code and t.Language = :language");
If I change the HQL to left outer join, I get the Path expected for join exception.
Can you help me with the following:
1- Do I need to change my mapping files?
2- If I can keep the mapping files as is, how write such a query in HQL?
3- How does HQL really works? Why such a simple outer join query is not working? I must be missing something here!
Edit:
Now I am using the following code based on the suggetion to use CreateSQL:
ISQLQuery query = session.CreateSQLQuery("select m.MedicineTypeID, t.Name, m.IsDeleted from MedicineType m left outer join Translation t on m.Code = t.Code and t.Language = :language");
query.SetString("language", language);
IList rawLookup = query.List();
IList medicineTypesLookup = new List(rawLookup.Count);
foreach (object[] lookup in rawLookup)
{
medicineTypesLookup.Add(new Lookup((int)lookup[0], (string)lookup[1], (bool)lookup[2]));
}
return medicineTypesLookup;
This is working however I want to use query.List() to get the result directly instead of converting it myself.
I tried to use query.AddEntity(typeof(Lookup)); but I get the exception NHibernate.MappingException: No persister for: DAL.Domain.Lookup.
The Lookup is just a POCO and doesn't map to any database table. Its mapping file is simply <import class="Lookup" />
Finally I found the answer:ISession session = NHibernateHelper.Session;
ISQLQuery query = session.CreateSQLQuery("select m.MedicineTypeID as ID, t.Name, m.IsDeleted from MedicineType m left outer join Translation t on m.Code = t.Code and t.Language = :language");
query.setString("language", language);
IList lookup = query.SetResultTransformer(Transformers.AliasToBean()).List();
return lookup;
And the lookup is a POCO class with a parameterless constructor and 3 properties ID, Name and IsDeleted.
I would like to thank Kelly and Diego Mijelshon for their hints. Although they don't provide the full answer the but using Session.CreateSqlQuery() was a very useful hint.
So the complete solution is Session.CreateSQLQuery and query.SetResultTransformer
Note: Transformers.AliasToBean() is so java.
Edit: http://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/impl/SQLQueryImpl.html for correct method of setString()
You must to define the relationship in the mappings or do a subquery