3

For some reason my class mapping doesn't work unless I use addAnnotatedClass(CategoryEntity.class) method. I've spent a lot of time already, but still can't figure out what's the problem here, could you tell me what I'm doing wrong?

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">admin</property>

        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL81Dialect</property>
        <property name="connection.url">jdbc:postgresql://localhost:5432/dvdrental</property>
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="entity.CategoryEntity"/>
    </session-factory>
</hibernate-configuration>

CategoryEntity.java

import javax.persistence.*;
import java.sql.Timestamp;

@Table(name = "category", schema = "public", catalog = "dvdrental")
@Entity
public class CategoryEntity {
    private Integer categoryId;
    private String name;
    private Timestamp lastUpdate;

    @Id
    @Column(name = "category_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    @Basic
    @Column(name = "name", nullable = false, length = 25)
    public String getName() {
        return name == null ? "" : name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "last_update", nullable = false)
    public Timestamp getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(Timestamp lastUpdate) {
        this.lastUpdate = lastUpdate;
    }
}

Main.java

public class Main {
    private static SessionFactory sessionFactory;

    public static void main(String[] args) {
        System.out.println("Hibernate tutorial");
        try {
            Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.out.println("Failed to create session factory");
            throw new ExceptionInInitializerError(e);
        }
        listAllCategories();

        sessionFactory.close();
    }

    private static void listAllCategories() {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            List<CategoryEntity> categories = session.createCriteria(CategoryEntity.class).list();
            for (CategoryEntity category : categories) {
                System.out.println("Category id = " + category.getCategoryId()
                        + ", name = " + category.getName() + ", last updated = " + category.getLastUpdate());
            }
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) { tx.rollback(); }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

enter image description here

Alexey Galanov
  • 421
  • 4
  • 21
  • I assume you're using packages so use the fully qualified classname. – Thomas Jun 02 '16 at 12:52
  • @Thomas could you point out where exactly should I do this? Everything looks fine for me – Alexey Galanov Jun 02 '16 at 13:18
  • Hmm I can't tell you exactly what to do since we're using Hibernate as a JPA provider and thus have our configuration in persistence.xml. However, have a look here: http://stackoverflow.com/questions/24089645/hibernate-configuration-file-cfg-xml-for-mapping-multiple-mysql-tables-in-the - this seems to fit your problem description. – Thomas Jun 02 '16 at 14:22
  • 1
    You might also have a look here:https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html which contains this line: `sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();` - that might be your problem, i.e. you don't create the session in a way that makes it understand/interpret annotations. – Thomas Jun 02 '16 at 14:29
  • A last thing you might check is whether `HibernateUtil.class.getResource("/hibernate.cfg.xml")` returns the correct file. – Thomas Jun 02 '16 at 14:33
  • @Thomas Thanks for your help, but I've already figured out what's the problem here, I'll post separate answer for everyone who encountered the same problem – Alexey Galanov Jun 02 '16 at 14:44
  • @AlexeyGalanov I am facing the same problem. Can you please tell how you resolved it . – DockYard Nov 15 '18 at 07:17

1 Answers1

4

The problem was the code I got from accepted answer Is buildSessionFactory() deprecated in hibernate 4?

        Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
        serviceRegistryBuilder.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Changed it to

sessionFactory = new Configuration().configure().buildSessionFactory();

and everything works fine now

Community
  • 1
  • 1
Alexey Galanov
  • 421
  • 4
  • 21
  • This doesn't make sense. Now you're avoiding loading your hibernate settings (unless you are setting them anywhere else) and you pretend it to work? – Pere Nov 28 '16 at 09:00
  • 1
    Pere, this works perfectly, only line needed for a session factory configuration, it solved our issue instantly – Steven Nov 20 '17 at 15:11
  • Same here, i was using literally the same code. Changed it to this oneliner and now everthing works. I swear, nothing in Spring/Hibernate makes sense. – Wesos de Queso Oct 17 '19 at 03:12