hibernate没有看到一个二传手

时间:2013-10-15 17:37:50

标签: java hibernate

我是hibernate的新手,我有愚蠢的问题。我的档案:

的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;
    }
}

和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();
        }
    }
}

代码正在编译,但在运行时我得到:

> 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

我发现类似的问题没有二传手。在我的案例中,系统说没有author_id的getter,但它在Books.java的第45行。

某人可以告诉我出了什么问题吗?也许还有一个我没看到的原因......

3 个答案:

答案 0 :(得分:5)

public int getAuthorId()
    {
        return author_id;
    }

应该是(observe,author_id)

public int getAuthor_id()
    {
        return author_id;
    }

或者将XML更新为蜘蛛评论的@Boris。

答案 1 :(得分:3)

据我所知,Hibernate需要一个你的Books类似乎没有的无参数构造函数。因此,即使您使保存部分正常工作,我认为您尝试加载时代码也会失败。

因此,创建一个构造函数:

public Books(){

}

Why does Hibernate require no argument constructor?

另外,如前所述,抛弃XML并使用JPA注释。根据标准Java约定,将Books重命名为Book,并从变量名中删除_。

艾伦

答案 2 :(得分:0)

我遇到过这个问题,我就这样解决了: 您应该在NetBeans IDE中生成构造函数,Getter和Setter(我正在使用IDE是netbeans),因此您必须按快捷键ALT + Insert(Mac上的CTLRL + I)。调用快捷方式后,将提供所有可能的生成器。