1

Consider an entity

Class Entity{
    String column1;
    String column2;
    String column3;
}

The generated query will be something like

Select column1, column2, column3, from Entity;

In which order the target columns (column1, column2, column3) are placed in the query?

Suppose I want the target columns to be generated in a particular order [ column3 -> column1 -> column2 ]. How can this be achieved?

Gaming God
  • 29
  • 8
  • Hibernate doesn't care about the order of column names in the database. It will generate the appropriate SELECT, INSERT, UPDATE and DELETE statements based on your entity mapping visit this https://stackoverflow.com/questions/1298322/wrong-ordering-in-generated-table-in-jpa – Navin Gelot Dec 24 '19 at 07:18
  • Thanks Navin. Seems like I need to use raw query as suggested by Tim. – Gaming God Dec 24 '19 at 08:22

1 Answers1

0

In general, the pattern you would use with Hibernate would be to execute an HQL query, which in turn would return a list of objects/entities. In this case, the concept of column order does not have much meaning. For example:

String hql = "FROM Entity AS E";
Query query = session.createQuery(hql);
List<Object> results = query.list();
for (Object o : results) {
    System.out.println("column1 is: " + ((Entity)o).getColumn1());
}

A Java POJO doesn't really have an ordering concept to its fields.

Your requirement might make sense in the context of executing a raw query against your SQL database. In that case, if you wanted a different order, then your select list should be providing that, e.g.

Transaction tx = session.beginTransaction();
SQLQuery query = session.createSQLQuery("select column3, column2, column2 from entity");
List<Object[]> rows = query.list();

In this case, we requested columns 3, 2, and 1, in that order.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks Tim. However I was looking for another approach rather than using raw query. I need to query tables with 100+ rows and they need to be some particular order. – Gaming God Dec 24 '19 at 08:22
  • @GamingGod In general, if you want to view columns in a result set in a particular order, you need to explicitly specify that order yourself. – Tim Biegeleisen Dec 24 '19 at 08:44