NHibernate not finding named query result sets in 2nd level cache - nhibernate

I have a simple unit test where I execute the same NHibernate named query 2 times (different session each time) with the identical parameter. It's a simple int parameter, and since my query is a named query I assume these 2 calls are identical and the results should be cached.
In fact, I can see in my log that the results ARE being cached, but with different keys. So, my 2nd query results are never found in cache.
here's a snip from my log (note how the keys are different):
(first query)
DEBUG NHibernate.Caches.SysCache2.SysCacheRegion [(null)] <(null)> -
adding new data: key= [snipped]... parameters: ['809']; named
parameters: {}#743460424 &
value=System.Collections.Generic.List`1[System.Object]
(second query)
DEBUG NHibernate.Caches.SysCache2.SysCacheRegion [(null)] <(null)> -
adding new data: key=[snipped]... parameters: ['809']; named
parameters: {}#704749285 &
value=System.Collections.Generic.List`1[System.Object]
I have NHibernate set up to use the query cache. And I have these queries set to cacheable=true. Don't know where else to look. Anyone have any suggestions?
Thanks
-Mike

Okay - i figured this out. I was executing my named query using the following syntax:
IQuery q = session.GetNamedQuery("MyQuery")
.SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO)))
.SetCacheable(true)
.SetCacheRegion("MyCacheRegion");
( which, I might add, is EXACTLY how the NHibernate docs tell you how to do it.. but I digress ;) )
If you use create a new AliasToBean Transformer for every query, then each query object (which is the key to the cache) will be unique and you will never get a cache hit. So, in short, if you do it like the nhib docs say then caching wont work.
Instead, create your transformer one time in a static member var and then use that for your query, and caching will work - like this:
private static IResultTransformer myTransformer = Transformers.AliasToBean(typeof(MyDTO))
...
IQuery q = session.GetNamedQuery("MyQuery")
.SetResultTransformer(myTransformer)
.SetCacheable(true)
.SetCacheRegion("MyCacheRegion");

Related

NHibernate - How to log Named Parameterised Query with parameter values?

I have a parameterised named Query like this :
Query moveOutQuery = session.createSQLQuery(moveOutQueryStr.toString())
.addEntity(MyClass.class)
.setParameter("assignmentStatus", Constants.CHECKED_OUT)
I want to see the actual SQL query with parameters filled in. However while debugging I only get the following query:
Select * from my_assignment WHERE assignment_status in ( :assignmentStatus )
Why isn't the assignmentStatus being substituted for its real value?
Why isn't the assignmentStatus being substituted for its real value?
This is because NHibernate use query parameters to input values. This is efficient in many cases and also helpful against SQL Injection attack. Parameters are sent separately. You can find them at the bottom if SQL is logged as explained below.
You may log each SQL to file as explained below.
This is implemented through log4net.dll; you need to add reference.
Add namespaces as below:
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
Configure log4net in NHibernate as below:
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders();
FileAppender fileAppender = new FileAppender();
fileAppender.Name = "NHFileAppender";
fileAppender.File = logFilePath;
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.Layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss}:%m%n%n");
fileAppender.ActivateOptions();
Logger logger = hierarchy.GetLogger("NHibernate.SQL") as Logger;
logger.Additivity = false;
logger.Level = Level.Debug;
logger.AddAppender(fileAppender);
hierarchy.Configured = true;
You also need to set ShowSql while configuration as below:
configuration.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true");
configuration.SetProperty(NHibernate.Cfg.Environment.FormatSql, "true");
You need to call this code once at startup of your application. Output log includes values of parameters as well.
Following is the code:
session.CreateSQLQuery("SELECT * FROM MyEntity WHERE MyProperty = :MyProperty")
.AddEntity(typeof(MyEntity))
.SetParameter("MyProperty", "filterValue")
.UniqueResult<MyEntity>();
Following is the logged query:
2020-01-09 14:25:39:
SELECT
*
FROM
MyEntity
WHERE
MyProperty = #p0;
#p0 = 'filterValue' [Type: String (4000:0:0)]
As you can see, parameter value filterValue is listed at the bottom.
This works for all query APIs like IQueryOver, IQuery, ISQLQuery etc.
This logs both success and failed statements. You can play with FileAppender and Logger class to meet your additional requirements.
Also refer PatternLayout from documentation. More details can also be found here, here and here. This Q/A discusses the same.
Following Q/A may also help:
Get executed SQL from nHibernate
Using log4net to write to different loggers
How to log SQL calls with NHibernate to the console of Visual Studio?
As you see, this logs the parameter values at bottom of the query. If you want those logged embedded in the query, please refer to this article.

ReleaseCumulativeFlowData and CardState

I'm trying to run a query against the ReleaseCumulativeFlowData object as follows:
((ReleaseObjectID = 12345) AND CardState="Accepted")
However, running the query results in the following error message:
OperationResultError
Could not read: could not read all instances of class
com.f4tech.slm.domain.reporting.ReleaseCumulativeFlowDataSet
Is this a bug in Rally?
WSAPI is very picky about the structure of the query. You have to include parentheses around chained query filters, so you would need something like the following:
((ReleaseObjectID = 12345) AND (CardState = "Accepted"))

Possible to get NHibernate to execute queries as EF?

Is there anyway to use NHibernate in such a way that it whould only execute the query/queries once the returned object of a query/statement is used.. just like EF doest it?
For most instances with EF it wont send and execute the actual query to the database until the returned object of a linq-"statement" is used.. for instance:
var x = for e in entities.MyTable
select e;
This aint executed yet!
Which meens that Im able to mofidy the x-objects "linq-query" however I like without actualt "pulling" any data from the database:
x = x.Where(i=>i.SomeThing = someThing);
Still aint executed!
x.ToList<MyTable>()
Now its executed!
But in NHibernate the query gets executed once the transaction gets closed or commited from what I have understod.. and in most cases thats done already in the repository. So you can't simply in any other place alter the query and then send it to the database. Cause the query is already sent and that whould mean that you later on only whould alter whats "displayed" from the result.
I might have gotten this al wrong so please correct me if I am wrong.
Huge thanks in advance!
You can try something like this using detached QueryOver
var query = QueryOver.Of<Customer>()
.Where(x => x.LastName == "Smith"); // query is not executed yet
query.GetExecutableQueryOver(session).List();
Good thing is that you can pass QueryOver objects and get it executed somewhere else.

Is is possible to use Postgresql's Explain to analyse queries generated by Grails GORM

I found and have used a closure that temporarily turns hibernate.SQL logging to Trace to allow me to see the exact queries that are generated. However I would like to be able to have PostgresQL's explain run automatically instead of having to pull out queries individually for analysis.
logging closure:
(found here: http://www.intelligrape.com/blog/2011/10/21/log-sql-in-grails-for-a-piece-of-code/)
public static def execute(Closure closure) {
Logger sqlLogger = Logger.getLogger("org.hibernate.SQL");
Logger transactionLogger = Logger.getLogger("org.hibernate.transaction");
Level currentLevel = sqlLogger.level
Level transLevel = transactionLogger.level
sqlLogger.setLevel(Level.TRACE)
transactionLogger.setLevel(Level.TRACE)
def result = closure.call()
sqlLogger.setLevel(currentLevel)
transactionLogger.setLevel(transLevel)
result
}
usage:
def result
execute{
result=Dog.createCriteria().list{
eq("breed","Greyhound")
}
}
I would like something that can be used in a similar way.
Is this something I could do with a sub-class of Criteria or Hibernate.Restrictions ?
Or is there something I'm missing in the docs on how to modify the SQL statement that is sent to the DB from GORM?
Thanks for any info.
Assuming you don't want all queries, but only the longer-running ones you might find the "auto explain" add-on for PostgreSQL useful.
http://www.postgresql.org/docs/9.1/static/auto-explain.html

2nd level cache problem with join query

I want to use Second level Cache for my query with eager loading(query is below wrote in 3 different ways, i use query cache). I have standard one to many association. I set entity cache for parent, child, and association between parent and class. And the 2nd level cache doesn't work because i got exceptions.
I wrote my query in 3 different way:
Criteria:
session.CreateCriteria<DictionaryMaster>().SetFetchMode("DictionaryItems", FetchMode.Eager)
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.SetCacheable(true).SetCacheMode(CacheMode.Normal)
.List<DictionaryMaster>().ToList();
When I invoked this query i got exception "Unable to perform find[SQL: SQL not available]"
I think that the problem exists because I use DistinctRootEntityResultTransformer transform. I will start create my custom transform class and I hope that will work.
Query over:
session.QueryOver<DictionaryMaster>().Fetch(x => x.DictionaryItems).Eager
.TransformUsing(new DistinctRootEntityResultTransformer())
.Cacheable().CacheMode(CacheMode.Normal)
.List<DictionaryMaster>().ToList();
Exception is the same as in Criteria.
Linq:
session.Query<DictionaryMaster>().Fetch(x => x.DictionaryItems).Cacheable().CacheMode(CacheMode.Normal).ToList();
Here error depends from the version of nhibernate in 3.1 a got this error https://nhibernate.jira.com/browse/NH-2587?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel
but in 3.2 version i got this: https://nhibernate.jira.com/browse/NH-2856
Thanks in advance
sJHony I have found solution, but for me is more like workaround. Therefore if you know any other solution give me sign.
I utilize QueryOver without any transformation, the fault of this solution is that the query return elements equal amount of childs. Next I retrieve not multiplied list in memory using distinct.
This solution is ok, but when we add one more Fetch for query, then collection in object also be multiplied, that is why i modified collection type from IList(Bag) to ISet(Set).
Code looks like:
var queryCacheResult =
session.QueryOver<DictionaryMaster>()
.Fetch(x => x.DictionaryItems).Eager
.Cacheable().CacheMode(CacheMode.Normal)
.List<DictionaryMaster>().ToList();
return queryCacheResult.Distinct(new KeyEqualityComparer<DictionaryMaster>(x => x.Code)).ToList();