1

I am new to hibernate and I have stupid problem. My files:

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>
        <property name="hibernate.connection.driver_class">
            org.postgresql.Driver
        </property>
        <!-- Assume test is the database name -->
        <property name="hibernate.connection.url">
            jdbc:postgresql://localhost/booktown
        </property>
        <property name="hibernate.connection.username">
            mirek
        </property>
        <mapping resource="Books.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

books.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="Books" table="books">
        <meta attribute="Książki w booktown">
            This class contains the employee detail.
        </meta>
        <id name="id" type="int" column="id">
            <generator class="native"/>
        </id>
        <property name="title" column="title" type="string"/>
        <property name="author_id" column="author_id" type="int"/>
        <property name="subject_id" column="subject_id" type="int"/>
    </class>
</hibernate-mapping>

Books.java

public class Books
{
    private int id;
    private String title;
    private int author_id;
    private int subject_id;

    public Books(String title, int author_id, int subject_id)
    {
        this.title = title;
        this.author_id = author_id;
        this.subject_id = subject_id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public void setAuthorId(int author_id)
    {
        this.author_id = author_id;
    }

    public void setSubjectId(int subject_id)
    {
        this.subject_id = subject_id;
    }

    public int getId()
    {
        return id;
    }

    public String getTitle()
    {
        return title;
    }

    public int getAuthorId()
    {
        return author_id;
    }

    public int getSubjectId()
    {
        return subject_id;
    }
}

and Booktown.java

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Booktown
{
    private static SessionFactory factory;
    private static ServiceRegistry serviceRegistry;

    public static void main(String[] args)
    {
        try
        {
            //private static SessionFactory configureSessionFactory() throws HibernateException {
                Configuration configuration = new Configuration();
                configuration.configure();
                serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
                factory = configuration.buildSessionFactory(serviceRegistry);
                //return factory;


            //factory = new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex)
        {
            System.err.println("Failed to create sessionFactory object." + ex.toString());
            throw new ExceptionInInitializerError(ex);
        }

        Booktown BT = new Booktown();
        /* Add few employee records in database */
        Integer bID1 = BT.addBook(10, "Jakiś napis", 10, 30);
        Integer bID2 = BT.addBook(20, "Jakiś inny napis", 10, 50);
        //Integer bID3 = BT.addBook(30, "John", 10000, 14);
        /* List down all the employees */
        BT.listBooks();
        /* Update employee's records */
        BT.updateBook(bID1, 5000);
        /* Delete an employee from the database */
        BT.deleteBook(bID2);
        /* List down new list of the employees */
        BT.listBooks();
    }

    /* Method to CREATE a book in the database */
    public Integer addBook(int bid, String fname, int lname, int salary)
    {
        Session session = factory.openSession();
        Transaction tx = null;
        Integer bID = null;
        try
        {
            tx = session.beginTransaction();
            Books book = new Books(fname, lname, salary);
            bid = (Integer) session.save(book);
            tx.commit();
        }
        catch (HibernateException e)
        {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
        return bID;
    }

    /* Method to READ all the books */
    public void listBooks()
    {
        Session session = factory.openSession();
        Transaction tx = null;
        try
        {
            tx = session.beginTransaction();
            List<Books> books = session.createQuery("FROM books").list();
            for (Iterator<Books> iterator = books.iterator(); iterator.hasNext();)
            {
                Books book = (Books) iterator.next();
                System.out.print("First Name: " + book.getTitle());
                System.out.print(" Last Name: " + book.getAuthorId());
                System.out.println(" Salary: " + book.getSubjectId());
            }
            tx.commit();
        }
        catch (HibernateException e)
        {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

    /* Method to UPDATE author for a book */
    public void updateBook(Integer bID, int auth)
    {
        Session session = factory.openSession();
        Transaction tx = null;
        try
        {
            tx = session.beginTransaction();
            Books book = (Books) session.get(Books.class, bID);
            book.setAuthorId(auth);
            session.update(book);
            tx.commit();
        }
        catch (HibernateException e)
        {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

    /* Method to DELETE a book from the records */
    public void deleteBook(Integer bID)
    {
        Session session = factory.openSession();
        Transaction tx = null;
        try
        {
            tx = session.beginTransaction();
            Books book = (Books) session.get(Books.class, bID);
            session.delete(book);
            tx.commit();
        }
        catch (HibernateException e)
        {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }
}

Code is compiling but at run I get:

> paź 15, 2013 8:44:38 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory   <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Failed to create sessionFactory object.org.hibernate.MappingException: Could not get   constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "main" java.lang.ExceptionInInitializerError
at Booktown.main(Booktown.java:34)
Caused by: org.hibernate.MappingException: Could not get constructor for  org.hibernate.persister.entity.SingleTableEntityPersister
at   org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:385)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
at Booktown.main(Booktown.java:25)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer   [org.hibernate.tuple.entity.PojoEntityTuplizer]
at  org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138)
at   org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341) at  org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at  org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
... 4 more
Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at  org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135)
... 13 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for author_id in class Books
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:316)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:310)
at org.hibernate.mapping.Property.getGetter(Property.java:321)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:444)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:200)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
... 18 more

I found similar problem there was no setter. In my case system says that there is no getter for author_id but it is at line 45 in Books.java.

Could sb tells me what is wrong? Maybe there is an other cause which I don't see...

E-Riz
  • 31,431
  • 9
  • 97
  • 134
user2883469
  • 11
  • 1
  • 2

3 Answers3

5
public int getAuthorId()
    {
        return author_id;
    }

should be (observe, author_id)

public int getAuthor_id()
    {
        return author_id;
    }

OR update XML as @Boris the spider commented.

kosa
  • 65,990
  • 13
  • 130
  • 167
3

As far as I know Hibernate requires a no-arg constructor which your Books class does seem to have. So even if you get the save part working I think your code will fail when you attempt to load.

Thus, create a constructor:

public Books(){

}

Why does Hibernate require no argument constructor?

Also, as pointed out previously ditch the XML and use JPA annotations. In line with standard Java conventions rename Books to Book and remove the _ from your variable names.

Alan

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110
0

I had once this problem and I fix it like that: You should Generate Constructor, Getters and Setters in NetBeans IDE ( I'm working with IDE is netbeans) so you have to press shortcut ALT+Insert (CTLRL+I on Mac). After invoking the shortcut, all possible generators are offered.

faith66
  • 43
  • 1
  • 1
  • 7