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();
To Read data:
- 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();
Notice: .list()
Question object assumes the table is called questions.
- 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();
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();
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();
To Delete:
String hql = "DELETE FROM Question WHERE id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", 1);
int result = query.executeUpdate();
Hope it helps.!
    
Top comments (0)