Hibernate Query

hibernate

// Pagination with Hibernate:
Query q = session.createQuery(“Some SQL Query”);
q.setFirstResult(50);
q.setMaxResults(100);
List cats = q.list();

Query query = session.createQuery("from UserDetails where userId > 5");
query.setFirstResult(5);
query.setMaxResult(25);
List<UserDetails> users = (List<UserDetails>) query.list();

Notice that in the query above, we use the name of the class, and the name
of the member variables.  We do not use the name of the table, and the name
of the column, and there is no "select *" part.  And instead of returning
a record set, Hiberate returns a list of objects.

Query query = session.createQuery("select userName from serDetails");
List<String> userNames = (List<String>) query.list();

Query query = session.createQuery("select userId, userName from UserDetails");
List<List<String>> rows = (List<List<String>>) query.list();

Query query = session.createQuery("select new map(userId, userName) from UserDetails");
List<Map> users = (List<Map>) query.list();

Query query = session.createQuery("select max(userId) from UserDetails");

Query query = session.createQuery("from UserDetails where userId > ?");
query.setInteger(0, Integer.parseInt(minUserId));

Query query = session.createQuery("from UserDetails where userId > :userId");
query.setInteger("userId", Integer.parseInt(minUserId));

@NamedQuery(name="UserDetails.byId", query="from UserDetails where userId=?");
// The @NamedQuery annotation is added to the class.

Query query = session.getNamedQuery("UserDetails.byId");
query.setInteger(0, 2);

@NamedNativeQuery(name="UserDetails.byName", query="select * from User_Details
  where username=?", resultClass=UserDetails.class)
query.setString(0, "User 2");

return (Professor) em.createQuery(
    "SELECT e FROM Professor e WHERE e.id.country = ?1 AND e.id.id = ?2")
    .setParameter(1, country).setParameter(2, id).getSingleResult();

Query query = em.createQuery("SELECT e FROM Professor e");
return (Collection<Professor>) query.getResultList();

public class JPAUtil {
  Statement st;

  public JPAUtil() throws Exception{
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa", "");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public void executeSQLCommand(String sql) throws Exception {
    st.executeUpdate(sql);
  }
  public void checkData(String sql) throws Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        } else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}

public class Main {
  public static void main(String[] a) throws Exception {
    JPAUtil util = new JPAUtil();

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
    EntityManager em = emf.createEntityManager();
    ProfessorService service = new ProfessorService(em);

    em.getTransaction().begin();

    service.createProfessor("country", 1, "name", 100);

    Professor emp = service.findProfessor("country", 1);
    System.out.println("Found " + emp);

    System.out.println("Professors:");
    for (Professor emp1 : service.findAllProfessors()) {
      System.out.println(emp1);
    }

    util.checkData("select * from Professor");

    em.getTransaction().commit();
    em.close();
    emf.close();
  }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License