Foros de discusión

Getting Records from 3 tables using Dynamic Query

thumbnail
Jay Trivedi, modificado hace 11 años.

Getting Records from 3 tables using Dynamic Query

Regular Member Mensajes: 109 Fecha de incorporación: 24/11/12 Mensajes recientes
I have 3 tables user_, userTracker, userTrackerPath

user_ has userId as Pk. which is Fk in userTracker Table.
userTracker has UserTrackerId as pk which is Fk in userTrackerPath Table.
and userTrackerPath has userTrackerPathId as Pk.

user_ tables has fields firstName, LastName, loginIp, lastLoginIp as fields
userTracker has fields remoteAddr, remoteHost as fields
userTrackerPath has fields path_, pathDate as fields.

All these are the fileds that i want.

I have written an sql query and it runs successfully for me, but i want the result using Dynamic query .

Here is my sql query.


select concat(U.firstName," ",U.lastName) as     FullName,U.loginIp,U.lastLoginIp,UT.remoteAddr,substring(UT.modifiedDate,1,10) as Date,UTP.path_ from demo.User_ U, demo.UserTracker UT, demo.UserTrackerPath UTP where ((U.userId=UT.userId) and (UT.userTrackerId=UTP.userTrackerId));


I wrote dynamic query with projections i am confused how will i be joining them.


//Dynamic Query For User Class

        DynamicQuery dynamicQuery_user = DynamicQueryFactoryUtil.forClass(User.class,PortalClassLoaderUtil.getClassLoader())
                .setProjection(ProjectionFactoryUtil.property("userId"))
                .setProjection(ProjectionFactoryUtil.property("firstName"))
                .setProjection(ProjectionFactoryUtil.property("lastName"))
                .setProjection(ProjectionFactoryUtil.property("loginIp"))
                .setProjection(ProjectionFactoryUtil.property("lastLoginIp"));

        //Dynamic Query For User and UserTracker Class

        DynamicQuery dynamicQuery_userTracker  = DynamicQueryFactoryUtil.forClass(UserTracker.class,PortalClassLoaderUtil.getClassLoader())
                .setProjection(ProjectionFactoryUtil.property("modifiedDate"))
                .setProjection(ProjectionFactoryUtil.property("remoteAddr"));


        //Dynamic Query for UserTracker and UserTrackerPath

        DynamicQuery dynamicQuery_userTrackerPath  = DynamicQueryFactoryUtil.forClass(UserTrackerPath.class,PortalClassLoaderUtil.getClassLoader())
                .setProjection(ProjectionFactoryUtil.property("path_"))
                .setProjection(ProjectionFactoryUtil.property("pathDate"));


but i am confused how will i be getting all this fields into single list.

I was successfully able to get User_ records by using


 DynamicQuery q = DynamicQueryFactoryUtil.forClass(User.class, PortalClassLoaderUtil.getClassLoader())
			     .add(
			    		 PropertyFactoryUtil.forName("userId")
			             .in(
			            		 DynamicQueryFactoryUtil.forClass(UserTracker.class, PortalClassLoaderUtil.getClassLoader())
			                     .setProjection(ProjectionFactoryUtil.property("userId"))
			                     .add(
			                    		 PropertyFactoryUtil.forName("userTrackerId").in
			                    		 (
			                    				 DynamicQueryFactoryUtil.forClass(UserTrackerPath.class, PortalClassLoaderUtil.getClassLoader())
			                    				 .setProjection(ProjectionFactoryUtil.property("userTrackerId"))
			                    		)
			                    	 )
			                )
			         );


but instead i need records from all the 3 tables...
Any Help ?? emoticon
thumbnail
Juhi Kumari, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Expert Mensajes: 347 Fecha de incorporación: 12/12/11 Mensajes recientes
Hi,

For this requirement you can go for Custom query. I think using Dynamic Query we can use only one table.

Regards
Juhi
thumbnail
David H Nebinger, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Liferay Legend Mensajes: 14916 Fecha de incorporación: 2/09/06 Mensajes recientes
Untrue. DQ can do joins with other tables.
thumbnail
Jay Trivedi, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Regular Member Mensajes: 109 Fecha de incorporación: 24/11/12 Mensajes recientes
Thanks David. It makes one side of coin clear keeping other side confused. is How?
How can we do that?

can you please project any views on dynamic query written above for two tables. to get all data of both tables.

Thanks Jay.
thumbnail
jelmer kuperus, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Liferay Legend Mensajes: 1191 Fecha de incorporación: 10/03/10 Mensajes recientes
You cannot do joins using Liferay I wrote more on why this is in this thread

I don't believe it's possible to write this particular query using a dynamic query but you can probably do it via custom sql. Try something like this :

        SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");

        Session session = null;
        try {
            session = sessionFactory.openSession();

            SQLQuery query = session.createSQLQuery(
                "select {U.*}, {UT .*}, {UTP.*} " +
                "from User_ U, UserTracker UT, UserTrackerPath UTP " + 
                "where U.userId=UT.userId and UT.userTrackerId=UTP.userTrackerId;");

            try {
                query.addEntity("U", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.UserImpl"));
                query.addEntity("UT", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.UserTrackerImpl"));
                query.addEntity("UTP", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.UserTrackerPathImpl"));
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e); // should never happen
            }

           // probably a list of object arrays containing a user, usertracker and usertrackerpath
           List results = QueryUtil.list(query, sessionFactory.getDialect(),  QueryUtil.ALL_POS, QueryUtil.ALL_POS);

        } finally {
            if (session != null) {
                sessionFactory.closeSession(session);
            }
        }
thumbnail
Jay Trivedi, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Regular Member Mensajes: 109 Fecha de incorporación: 24/11/12 Mensajes recientes
Thanks Jelmer, but i am wondering since here there are three class i am going to use then what should i be writing in
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
thumbnail
jelmer kuperus, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Liferay Legend Mensajes: 1191 Fecha de incorporación: 10/03/10 Mensajes recientes
but i am wondering since here there are three class i am going to use then what should i be writing in
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");


Exactly that, liferaySessionFactory is just the name of the spring bean, its the same regardless of what entity you retrieve
thumbnail
Gnaniyar Zubair, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Liferay Master Mensajes: 722 Fecha de incorporación: 19/12/07 Mensajes recientes
Somewhere I have seen this code given by Jonas : But I didn't check. Please try this :

/* DynamicQuery dq0 = DynamicQueryFactoryUtil.forClass(JournalArticle.class, "journalarticle")
.setProjection(ProjectionFactoryUtil.property("resourcePrimKey"))
.add(PropertyFactoryUtil.forName("journalarticle.companyId").eqProperty("tagsasset.companyId"))
.add(PropertyFactoryUtil.forName("journalarticle.groupId").eqProperty("tagsasset.groupId"))
.add(PropertyFactoryUtil.forName("journalarticle.type").eq("article-content"));
DynamicQuery query = DynamicQueryFactoryUtil.forClass(TagsAsset.class, "tagsasset")
.add(PropertyFactoryUtil.forName("tagsasset.classPK").in(dq0))
.addOrder(OrderFactoryUtil.desc("tagsasset.viewCount"));*/
thumbnail
Jay Trivedi, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Regular Member Mensajes: 109 Fecha de incorporación: 24/11/12 Mensajes recientes
Thanks a Lot , I will update success trails.
emoticon
thumbnail
Jay Trivedi, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query

Regular Member Mensajes: 109 Fecha de incorporación: 24/11/12 Mensajes recientes
I tired Out an example to join 2 tables User_ and UserTracker as userId is common between them.


DynamicQuery dq0 = DynamicQueryFactoryUtil.forClass(User.class, "user",PortalClassLoaderUtil.getClassLoader())
			.setProjection(ProjectionFactoryUtil.property("user.userId"))
			.add(PropertyFactoryUtil.forName("user.userId").eqProperty("usertracker.userId"));
			DynamicQuery query = DynamicQueryFactoryUtil.forClass(UserTracker.class, "usertracker",PortalClassLoaderUtil.getClassLoader())
			.add(PropertyFactoryUtil.forName("usertracker.userId").in(dq0));
			
			List temp = new ArrayList();
			temp.addAll(UserTrackerLocalServiceUtil.dynamicQuery(query));


it returns all fields of UserTracker but we also want fields of User Table, What if we want all the fields from both table to get displayed.
ex. Select * from User_ u , UserTracker ut where u.userId = ut.userId.

Any suggestions. emoticon
thumbnail
meera prince, modificado hace 11 años.

RE: Getting Records from 3 tables using Dynamic Query (Respuesta)

Liferay Legend Mensajes: 1111 Fecha de incorporación: 8/02/11 Mensajes recientes