2

How can I print out an entire table from my database and its contents using Java and Hibernate?

My code thus far only prints one line of information that I need. It only prints the author:

package models;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dao.HibernateDataDAO;
import hibernate.Books;

public class TestModel {
    HibernateDataDAO data;
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void test() {
        System.out.println("Testing hibernate");
        //This Books is just a test, in the real implementation it will be added by the user.
        Books books = new Books();

        books.setTitle("A Game of Thrones");
        books.setAuthor("George RR Martin");

        data.insertBooks(books);

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        books = (Books) session.get(hibernate.Books.class, 1);
        System.out.println(books.getAuthor());


        //int id = 3;
        //We set this as 'increment' so that keys are set by database and not by users.
        //data.deleteBooks(books, id);
    }

    public HibernateDataDAO getData() {
        return data;
    }

    public void setData(HibernateDataDAO data) {
        this.data = data;
    }   
}

My table is called books. and there are 3 columns in it: booksKey, title, and author. booksKey is an integer, title/author are strings. How can I print the entire table so that it prints out all the rows of information?

I tried modifying the above code and doing this, however, nothing printed:

    Query query = session.createSQLQuery("select *from books");
    List<Books> list = query.list();
    for(Books test: list) {
        System.out.println(test.getAuthor());
    }

If someone can please help-preferably show me what code to add/fix, that would be awesome. I can't figure this out at all!

HibernateDataDAO:

package dao;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import hibernate.Books;
import hibernate.Music;
import hibernate.Contacts;
import hibernate.Movies;

//DAO = data access object.
public class HibernateDataDAO {
    private SessionFactory sessionFactory;
    private Transaction transaction;

    public void insertBooks(Books books) {
        Session session = sessionFactory.openSession();

        try {
            transaction = session.beginTransaction();
            session.save(books);
            transaction.commit();
        } 
        catch (Exception e) {
             if (transaction != null) transaction.rollback();
             throw e;
        }
        finally {
             session.close();
        }
    }

    public void deleteBooks(Books books, int booksKey){
        Session session = sessionFactory.openSession();
        try{
            transaction = session.beginTransaction();
            Object persistentInstance = session.load(hibernate.Books.class, booksKey);
            if (persistentInstance != null) {
                session.delete(persistentInstance);
            }
            transaction.commit();
        }catch(HibernateException e){
            if(transaction!= null) transaction.rollback();
            e.printStackTrace();
        }
        finally{
            session.close();
        }
    }

    public void insertMusic(Music music) {
        Session session = sessionFactory.openSession();

        try {
            transaction = session.beginTransaction();
            session.save(music);
            transaction.commit();
        } 
        catch (Exception e) {
             if (transaction != null) transaction.rollback();
             throw e;
        }
        finally {
             session.close();
        }
    }

    public void deleteMusic(Music music, int musicKey){
        Session session = sessionFactory.openSession();
        try{
            transaction = session.beginTransaction();
            Object persistentInstance = session.load(hibernate.Music.class, musicKey);
            if (persistentInstance != null) {
                session.delete(persistentInstance);
            }
            transaction.commit();
        }catch(HibernateException e){
            if(transaction!= null) transaction.rollback();
            e.printStackTrace();
        }
        finally{
            session.close();
        }
    }

    public void insertMovies(Movies movies) {
        Session session = sessionFactory.openSession();

        try {
            transaction = session.beginTransaction();
            session.save(movies);
            transaction.commit();
        } 
        catch (Exception e) {
             if (transaction != null) transaction.rollback();
             throw e;
        }
        finally {
             session.close();
        }
    }

    public void deleteMovies(Movies movies, int movieKey){
        Session session = sessionFactory.openSession();
        try{
            transaction = session.beginTransaction();
            Object persistentInstance = session.load(hibernate.Movies.class, movieKey);
            if (persistentInstance != null) {
                session.delete(persistentInstance);
            }
            transaction.commit();
        }catch(HibernateException e){
            if(transaction!= null) transaction.rollback();
            e.printStackTrace();
        }
        finally{
            session.close();
        }
    }

    public void insertContacts(Contacts contacts) {
        Session session = sessionFactory.openSession();

        try {
            transaction = session.beginTransaction();
            session.save(contacts);
            transaction.commit();
        } 
        catch (Exception e) {
             if (transaction != null) transaction.rollback();
             throw e;
        }
        finally {
             session.close();
        }
    }

    public void deleteContacts(Contacts contacts, int contactKey){
        Session session = sessionFactory.openSession();
        try{
            transaction = session.beginTransaction();
            Object persistentInstance = session.load(hibernate.Contacts.class, contactKey);
            if (persistentInstance != null) {
                session.delete(persistentInstance);
            }
            transaction.commit();
        }catch(HibernateException e){
            if(transaction!= null) transaction.rollback();
            e.printStackTrace();
        }
        finally{
            session.close();
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }       
}
ihoaxed
  • 127
  • 2
  • 16
  • What does query.list() do? what Query class are you using? did you check the contents of list before iterating over it? – Stultuske Feb 03 '16 at 09:20
  • Honestly, I have no clue. I copied that solution from another post and edited it so it fits my code. It was from here: http://stackoverflow.com/a/16372978/5735034 – ihoaxed Feb 03 '16 at 09:41
  • Well, there's your problem. don't just copy-paste, try and write code you actually understand. For all we know, your ide imported a different Query class. – Stultuske Feb 03 '16 at 09:44
  • hi @ihoaxed! if nothing gets printed then there are possibilities that data wasn't inserted correctly. Can you please post the contents of `HibernateDataDAO` ? – Raman Sahasi Feb 03 '16 at 14:40
  • @Rdx I went ahead and updated the post with the HibernateDataDAO. Please take a look. I still haven't figured this out :( – ihoaxed Feb 03 '16 at 19:26

2 Answers2

1

Try this:

Criteria criteria = session.createCriteria(Books.class);
List<Books> list = criteria.list();
for(Books test: list) {
    System.out.println(test.getBooksKey + " " + test.getAuthor() + " " + test.getTitle());
}

If you there's any error, then please let me know about it.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

You should change your code like following;

Query qry=session.createQuery("from  books");
List<Books> user=(List<Books>) qry.list();
session.getTransaction().commit();
session.close();
List<Books> list = query.list();
for(Books test: list) {
    System.out.println(test.getAuthor());
}
java.nazif
  • 713
  • 1
  • 9
  • 18
  • Hey, I tried doing that but get the following stacktrace: `org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: books is not mapped [from books] org.hibernate.hql.internal.ast.QuerySyntaxException: books is not mapped [from books] org.hibernate.hql.internal.ast.QuerySyntaxException: books is not mapped` I did map books in my xml file. Any idea why this could be happening? – ihoaxed Feb 03 '16 at 19:52