How to access Liferays connection tables like Users_Orgs

Ok, this is something that has been bugging me for weeks :

How do you create a DynamicQuery that is able to access all the n- to m tables that Liferay offers ?
Tables like Users_Orgs or Users_Roles ?  Normally you would have to retrieve the User and then retrieve the Orgs by calling a method on that user that uses a Finder which has some custom sql and ... well: it´s not very performant. You have to do it for every individual user, you´re out of your DynamicQuery and your application gets slower.

You could write some custom sql, or you might do the follwing:

Use the Liferay Service Builder to access the tables, Liferay hides from you.

Create a new service.xml or add the following to an already existing one :

<entity name="Users_Orgs" local-service="true" remote-service="false">
<column name="userId" type="long" primary="true" />
<column name="organizationId" type="long" />

Your name has to match the table you want to access. Then generate your service, and Liferay creates a Users_Orgs class for you. This you can use to access the no-longer hidden table by a DynamicQuery:

DynamicQuery blogsQuery = DynamicQueryFactoryUtil.forClass( Users_Orgs.class, PortalClassLoaderUtil.getClassLoader());

On the downside I have to say that there is a reason, that those tables aren´t accessible. So if I were you I´d remove all methods from the newly created Service that writes to that table.

If you liked this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.