0

I have two classes User and Application.

User has one to many mapping to application. User has a lot of fields, some are pretty big ones like description. I don't want to load all the fields of the user when I want to use it to see the relationship between user and application so I created a proxy class that has username and a collection of application. How do I the two tables to this class? Or what is the best practice?

update :

@Entity
public class UserProfile implements Serializable
{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long                    id;
    private String                  userName;
    private String                  password;
    @OneToMany
    @JoinTable(name = "userapplicationlink", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "appId"))
    private Collection<Application> applications; 

}


@Entity
public class Application
{
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE)
   private int     id;
   private String name;
   private String url;
}

main()
{
    UserProfile user1 = new UserProfile();
    user1.setUserName("sasd");
    user1.setPassword("123");

    Application app = new Application();
    app.setName("User Application");
    app.setPriority(1);
    app.setUrl("/user.do");
    app.setDescription("app");
    user1.setApplications(new ArrayList());
    user1.getApplications().add(app);

    SessionFactory sessionFac = new Configuration().configure().buildSessionFactory();
    Session session = sessionFac.openSession();
    session.beginTransaction();

    session.save(user1);
    session.save(app);

    session.getTransaction().commit();
    System.out.println("End");
    session.close();
    sessionFac.close();


    sessionFac = new Configuration().configure().buildSessionFactory();
    session = sessionFac.openSession();
    session.beginTransaction();
    try
    {
        Query query = session.createQuery("SELECT NEW empire.erp.server.db.UserNameAndApplications(u.userName, u.applications) FROM UserProfile u JOIN FETCH u.applications");
        List result = query.list();
        session.getTransaction().commit();
        session.close();

    }
    finally
    {
        session.close();
        sessionFac.close();
    }
}

Stack trace

Exception in thread "main" org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=null,role=empire.erp.server.db.UserProfile.applications,tableName=Application,tableAlias=applicatio2_,origin=UserProfile userprofil0_,columns={userprofil0_.id ,className=empire.erp.server.db.Application}}] [SELECT NEW empire.erp.server.db.UserNameAndApplications(u.userName, u.applications) FROM empire.erp.server.db.UserProfile u JOIN FETCH u.applications] at org.hibernate.QueryException.generateQueryException(QueryException.java:120) at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142) at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:115) at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:76) at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150) at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302) at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240) at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1907) at empire.erp.server.db.UserProfile.main(UserProfile.java:216) Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=null,role=empire.erp.server.db.UserProfile.applications,tableName=Application,tableAlias=applicatio2_,origin=UserProfile userprofil0_,columns={userprofil0_.id ,className=empire.erp.server.db.Application}}] at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:214) at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:991) at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:759) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:675) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190) ... 8 more

Update 2: running query without fetch

Hibernate: select userprofil0_.userName as col_0_0_, . as col_1_0_ from UserProfile userprofil0_ inner join userapplicationlink applicatio1_ on userprofil0_.id=applicatio1_.userId inner join Application applicatio2_ on applicatio1_.appId=applicatio2_.id inner join userapplicationlink applicatio3_ on userprofil0_.id=applicatio3_.userId inner join Application applicatio4_ on applicatio3_.appId=applicatio4_.id May 07, 2016 4:17:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 0, SQLState: 42601 May 07, 2016 4:17:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: ERROR: syntax error at or near "." Position: 43 May 07, 2016 4:17:21 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/optimalyou] Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79) at org.hibernate.loader.Loader.getResultSet(Loader.java:2115) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874) at org.hibernate.loader.Loader.doQuery(Loader.java:919) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) at org.hibernate.loader.Loader.doList(Loader.java:2610) at org.hibernate.loader.Loader.doList(Loader.java:2593) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422) at org.hibernate.loader.Loader.list(Loader.java:2417) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339) at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) at empire.erp.server.db.UserProfile.main(UserProfile.java:217) Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "." Position: 43 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2284) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2003) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:200) at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:424) at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:161) at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:114) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70) ... 15 more

Cybermonk
  • 514
  • 1
  • 6
  • 28
  • can you paste you Entity class you tried so far? – Gautam Savaliya May 07 '16 at 08:16
  • 1
    See 19.1.7.https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html Optimising columns reads is only useful in extreme cases. – Alan Hay May 07 '16 at 10:01
  • Yes I know, this is just an pseudo problem. The real use case is I have two tables, lets say there is one to many relation, and I'd be querying say some 10000 records. but i am not interested in all the columns in both the tables, just two or three integer columns at most. – Cybermonk May 07 '16 at 10:18

1 Answers1

0

Had to use an alias for the collection. Not sure why though. The proper HQL is

 SELECT NEW empire.erp.server.db.UserNameAndApplications(u.userName, app) FROM UserProfile u JOIN u.applications app
Cybermonk
  • 514
  • 1
  • 6
  • 28