Say there is a User table with structure:
User
- List item
- userId (PK)
- company (PK)
- userName
- address ...etc
And I want to retrieve users only for the current company (company can be changed by the user through UI, so the company is a runtime parameter)
Similarly there are many other tables that have similar structure with common column (company), and I want to restrict data to only the current company, so I am using hibernate filter to filter out data.
Hibernate annotations:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">Dialect....</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>User</value>
.....
</list>
</property>
</bean>
Filter definitions:
@org.hibernate.annotations.FilterDef(name="restrictToCurrentCompany", parameters = {@org.hibernate.annotations.ParamDef( name = "currentCompanyNumber", type = "int" ) } ) @Entity @Table(name = "USER") @org.hibernate.annotations.Filter( name = "restrictToCurrentCompany", condition="company = :currentCompanyNumber" ) public class User implements Serializable { private int company; private String userName; ...etc.. }
Dao's:
@Repository @Transactional(readOnly = true) public class UserDAOImpl implements UserDAO { @Autowired(required = true) private SessionFactory sessionFactory; public Set getUsers(){ .....Criteria queries to retrieve users for the current company } private Session getSession(){ return sessionFactory.getCurrentSession(); } }
If I change the getSession like so;
private Session getSession(){
Session session = sessionFactory.getCurrentSession();
Filter filter = session.enableFilter("restrictToCurrentCompany");
filter.setParameter("currentCompanyNumber", UserUtils.getCurrentCompany());
return sessionFactory.getCurrentSession();
}
then I can enable the filter and everything looks good, but instead of enabling the filter during getting session is there a simpler alternative to apply and enable filter for the whole session factory/application level? If so, how could I do so using spring configuration?
I tried hooking into hibernate interceptors (pre-load event listerns) but I am bit unsure if this is a correct approach or should I rather use the getSession method listed above to enable filters?