Hibernate实体类映射不起作用

时间:2016-06-02 12:47:50

标签: java hibernate

由于某些原因,除非我使用addAnnotatedClass(CategoryEntity.class)方法,否则我的类映射不起作用。我已经花了很多时间,但仍然无法弄清楚这里的问题是什么,你能告诉我我做错了吗?

的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

2 个答案:

答案 0 :(得分:2)

问题是我从接受的答案Is buildSessionFactory() deprecated in hibernate 4?

获得的代码
public class LambdaScope {
    public void doWork() {
        Runnable runner1 = new Runnable() {
            @Override
            public void run() {
                System.out.println(toString());
            }
        };
        new Thread(runner1).start();
    }
    @Override
    public String toString() {
        return "Outer class: " + this.getClass();
    }

    public static void main(String[] args) {
        LambdaScope ls = new LambdaScope();
        ls.doWork();
    }
}

将其更改为

        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);

现在一切正常

答案 1 :(得分:0)

在使用hibernate的第5版时遇到了同样的问题:我的hibernate.cfg.xml中的映射被忽略了。为了解决这个问题,我更改了负责创建sessionFactory对象的代码,使其成为以下内容:

final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        return sessionFactory;
    } catch (Exception e) {
        StandardServiceRegistryBuilder.destroy(registry);
        throw new RuntimeException("SeesionFactory cannot be created");
    }

我的整个HibernateUtil类看起来像这样:

public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {   
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        return sessionFactory;
    } catch (Exception e) {
        StandardServiceRegistryBuilder.destroy(registry);
        throw new RuntimeException("SeesionFactory cannot be created");
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

我正在使用我的“主”类中的这个类来处理我的实体。例如:

public static void main(String[] args) {
    try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();
        User user = new User();
        // setting fields
        session.save(user);
        session.getTransaction().commit();
        session.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}