spring / hibernate - filter by current user id -


i have table companylist in oracle database :

cmp_id integer -- id of company cmp_name varchar2 -- name of company usr_id integer -- foreign key users table 

i have spring 3 mvc app configured using annotations, pojos , dao objects (companydao) using hibernate retrieve exemple list of companies.

companydao :

@transactional     public set<company> findallcompanys() throws dataaccessexception {          return findallcompanies(-1, -1);     }      @suppresswarnings("unchecked")     @transactional     public set<company> findallcompanies(int startresult, int maxrows) throws dataaccessexception {         query query = createnamedquery("findallcompanies", startresult, maxrows);         return new linkedhashset<company>(query.getresultlist());     } 

and company domain :

@entity @namedqueries( {         @namedquery(name = "findallcompanies", query = "select mycompany company mycompany")}) ... public class company implements serializable { ... 

then setup spring security, pages require identification.

what best way filter rows returned companydao, using user id of current logged in user session ?

short answer: securitycontextholder.

slightly longer answer: if user entity parent side of user_id foreign key relationship implements userdetails interface, user entity can used directly in spring's security context.

you can call securitycontextholder.getcontext() method either dao layer or layer above it...doesn't matter because instance returned scoped thread local of request.

you can userdetails context instance, cast user entity , pass named parameter dao call.

as quick followup, realize original question implied you'd run named query exists , filter out non-matching companies. can still use approach comparing users associated company user security context, in general wouldn't recommend approach; ask database need.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -