2

In my exsisting project i have aprox. 70+ tables in database,i m using Hibernate as Data Access Layer,so every query is done by using criteria API/HQL/Named Query. Now we are adding one column in 40+ tables (transaction tables) called isDeleted which is true or false.

Now in my current project i have to fetch records by adding an extra Restrictions\ Where Clause on that tables,which takes more time.

Is there any way so that i can intercept each database query(criteria API/HQL/Named Query) so that i can add where clause on respective models/tables.

Hibernate Session------>HQL/Named(native) Query---->Interceptor----->will add where clause on REQUIRED TABLES---->send it further to DB

1 Answer 1

1

Yes, you can use dynamic filters in combination with interceptors.

http://nhforge.org/wikis/howtonh/contextual-data-using-nhibernate-filters.aspx

For all the entities that have such an isDeleted property, I'd let them implement a certain interface where this property is defined. For instance:

interface ISoftDeletable
{
   bool IsDeleted { get; }
}

class SomeEntity : ISoftDeletable {}

(note that i use C# to explain my point, but I guess it'll be quite similar in java)

Then, you can define a filter-definition when creating your Hibernate configuration:

var softDeleteFilterParametersType = new Dictionary<string, NHibernate.Type.IType> (1);
softDeleteFilterParametersType.Add ("p_isDeleted", NHibernateUtil.Bool);

cfg.AddFilterDefinition (new FilterDefinition("SoftDeleteFilter", ":p_isDeleted = isDeleted", softDeleteFilterParametersType, false);

Then, you should add the filter to each mapped class that implements the ISoftDeletable interface:

foreach( var m in cfg.ClassMappings )
{
    if( typeof(ISoftDeletable).IsAssignableFrom (m.MappedClass) )
    {
        Property delColumn = m.GetProperty ("IsDeleted");

        m.AddFilter ("SoftDeleteFilter", ":p_isDeleted = " + delColumn.ColumnIterator.First().Name);
    }
}

Then, you still have to create an interceptor which sets the value of the parameter to true or false, depending on what you want to do.

Perhaps you can even hardcode the value of the parameter in your filterclause (if you always want to retrieve non-deleted items), which would make the code above simpler I guess.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Sir for quick reply can you provide some demo code for the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.