2013-10-15 4 views
1

Я новичок в спящем режиме, и у меня есть глупая проблема. Мои файлы: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, но она находится в строке 45 в Books.java.

Может ли sb сказать мне, что не так? Может быть, есть другая причина, которую я не вижу ...

+1

В следующий раз отформатируйте свой XML и разместите меньше кода. Зачем нам нужен весь код? –

ответ

5
public int getAuthorId() 
    { 
     return author_id; 
    } 

должно быть (наблюдать, author_id)

public int getAuthor_id() 
    { 
     return author_id; 
    } 

ИЛИ обновление XML, как @Boris паук комментировал.

+3

Я бы предложил изменить XML, а не getter. –

+0

@BoristheSpider: Хороший подход. – kosa

+5

Или еще лучше использовать конфигурацию на основе аннотаций. – chrylis

3

Насколько я знаю, Hibernate требует конструктора no-arg, который, по-видимому, имеет класс ваших книг. Поэтому, даже если вы получите работу с сохранением, я думаю, что ваш код не удастся при попытке загрузить.

Таким образом, создать конструктор:

public Books(){ 

} 

Why does Hibernate require no argument constructor?

Кроме того, как указывалось ранее канаву XML и использовать JPA аннотации. В соответствии со стандартными соглашениями Java переименуйте книги в книгу и удалите _ из ваших имен переменных.

Алан

0

Я был один раз эту проблему и исправить это так: вы должны создать конструктор, геттеры и сеттеры в среде IDE NetBeans (я работаю с IDE является NetBeans), так что вы должны нажать ярлык ALT + Вставить (CTLRL + I на Mac). После вызова ярлыка предлагаются все возможные генераторы.

Смежные вопросы