DEV Community

Keval Domadia
Keval Domadia

Posted on

Understanding HQL from Zero to Hero!

To Create data:

String hql = "INSERT INTO Question(title, topic_id, answer) VALUES(:title, :topic_id, :answer)";
Query query = session.createQuery(hql);
query.setParameter("title", "What is life and universe?");
query.setParameter("topic_id", 42);
query.setParameter("answer", "Discovery");
int result = query.executeUpdate();
Enter fullscreen mode Exit fullscreen mode

To Read data:

  1. To List data - as in multiple rows.
String hql = "FROM Question WHERE topic_id > :topic_id";
Query query = session.createQuery(hql);
query.setParameter("topic_id", 42);
List<Question> questions = query.list();

Enter fullscreen mode Exit fullscreen mode

Notice: .list()

Question object assumes the table is called questions.

  1. To List data - as in a single row.
String hql = "FROM Question WHERE topic_id > :topic_id";
Query query = session.createQuery(hql);
query.setParameter("topic_id", 42);
List<Question> singleQuestion = query.uniqueResult();
Enter fullscreen mode Exit fullscreen mode

However, IF it is not unique as in key unique, which would be the case in list of Topics.

Use the list() but also use setMaxResult(). Example:

String hql = "FROM Question WHERE topic_id > :topic_id";
Query query = session.createQuery(hql);
query.setParameter("topic_id", 42);
query.setMaxResult(1);
List<Question> singleQuestion = query.uniqueResult();
Enter fullscreen mode Exit fullscreen mode

Incase you are fetching data in a paginated fashion, example page 2 will show results from 20 to 30
then use the above in combination with setFirstResult(20) with setMaxResult(10). Take it that setMaxResult is LIMIT in SQL and setFirstResult is OFFSET.

To Update:

String hql = "UPDATE Question SET topic_id = :topic_id WHERE id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", 1);
query.setParameter("topic_id", 42);
int result = query.executeUpdate();
Enter fullscreen mode Exit fullscreen mode

To Delete:

String hql = "DELETE FROM Question WHERE id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", 1);
int result = query.executeUpdate();
Enter fullscreen mode Exit fullscreen mode

Hope it helps.!

Top comments (0)