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

7
  • I assume you're using packages so use the fully qualified classname. Commented Jun 2, 2016 at 12:52
  • @Thomas could you point out where exactly should I do this? Everything looks fine for me Commented Jun 2, 2016 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: stackoverflow.com/questions/24089645/… - this seems to fit your problem description. Commented Jun 2, 2016 at 14:22
  • 1
    You might also have a look here:docs.jboss.org/hibernate/stable/annotations/reference/en/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. Commented Jun 2, 2016 at 14:29
  • A last thing you might check is whether HibernateUtil.class.getResource("/hibernate.cfg.xml") returns the correct file. Commented Jun 2, 2016 at 14:33

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

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, this works perfectly, only line needed for a session factory configuration, it solved our issue instantly
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.