Home > JPA - Hibernate > Records without mapping – SqlResultSetMapping

Records without mapping – SqlResultSetMapping

If you just want to write a SELECT command without an entity, you can use NativeQuery. But this is not as easy as you think. Especially if it has not. Here is an example;

At first you have to make SqlResultSetMapping. With SqlResultSetMapping you have the possibility to save results in various Entities or results only scalar quantities, so no entity to work.

The following code must be added to any entity class ;

@Entity
@Table(name = "rights")
@SqlResultSetMapping(name = "userRightResult",
  columns = { @ColumnResult(name = "name"),
              @ColumnResult(name = "userright")
})
public class Rights implements Serializable {

 

for other opportunities at SqlResultSetMapping, see

http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

Once you have created SqlResultSetMapping, you can now write his native query;

List<Object[]> rights = entityManager.createNativeQuery(
    "select name, userright from rights" ,"userRightResult")
  .getResultList();
// so get results back as Object []
// and now you can output results
for(Object object : rights){
   Object[] obj = (Object[]) object;
   System.out.println((String)obj[0]); // name
   System.out.println((String)obj[1]); // userright
}
Advertisements
  1. Ezequiel
    1. March 2013 at 21:46

    Thanx!!!!! Very much!!!!

  2. sandeep
    21. March 2014 at 03:04

    Thank you!! You saved my day 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: