hibernate无法识别我的实体

时间:2016-02-27 21:52:37

标签: java hibernate

我正在尝试学习hibernate并且我遇到了hibernate注释的问题,问题是hibernate没有接缝来识别我的实体用户

package com.mycompanyname.myapp;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="FINANCES_USER")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="USER_ID")
private Long userId;

@Column(name="FIRST_NAME")
private String firstName;

@Column(name="LAST_NAME")
private String lastName;

@Column(name="BIRTH_DATE")
private Date birthDate;

@Column(name="EMAIL_ADDRESS")
private String emailAddress;

@Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;

@Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;

@Column(name="CREATED_DATE")
private Date createdDate;

@Column(name="CREATED_BY")
private String createdBy;

public Long getUserId() {
    return userId;
}

public void setUserId(Long userId) {
    this.userId = userId;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Date getBirthDate() {
    return birthDate;
}

public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
}

public String getEmailAddress() {
    return emailAddress;
}

public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
}

public Date getLastUpdatedDate() {
    return lastUpdatedDate;
}

public void setLastUpdatedDate(Date lastUpdatedDate) {
    this.lastUpdatedDate = lastUpdatedDate;
}

public String getLastUpdatedBy() {
    return lastUpdatedBy;
}

public void setLastUpdatedBy(String lastUpdatedBy) {
    this.lastUpdatedBy = lastUpdatedBy;
}

public Date getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
}

public String getCreatedBy() {
    return createdBy;
}

public void setCreatedBy(String createdBy) {
    this.createdBy = createdBy;
}

}

这是我的主要

package com.mycompanyname.myapp;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.MetadataSources;
import com.mycompanyname.myapp.User;
public class Application {

    public static void main(String[] args) {
        // A SessionFactory is set up once for an application!
        SessionFactory sessionFactory =null;
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
             sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.
            StandardServiceRegistryBuilder.destroy( registry );
        }

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.getTransaction().commit();
    User user1 = new User();
    user1.setUserId((long)234);
    session.save(user1);
    //session.close();
    }

}

这是我的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="HibernateUtil">
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.password">database</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/financialanalysis</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <mapping class="com.mycompanyname.myapp.User"/>
    </session-factory>
</hibernate-configuration>

此异常不断弹出

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.mycompanyname.myapp.User
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
    at com.mycompanyname.myapp.Application.main(Application.java:32)

所以我做错了什么?

3 个答案:

答案 0 :(得分:0)

我认为配置SessionFactory的方式存在问题。我根据您提供的源代码创建了一个示例应用程序。我怀疑这条线路有问题。

sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();

所以我会采用不同的方法配置像这样的会话工厂。

 SessionFactory sessionFactory =null;

    try {
        Configuration configuration = new Configuration();
        configuration.configure();
        final ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(registry);
    }
    catch (Exception e) {
        e.printStackTrace();
        sessionFactory.close();
    }

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.getTransaction().commit();
    User user1 = new User();
    user1.setUserId((long)234);
    session.save(user1);
    session.close();

查看源代码configuration.configure()方法还会在类路径中找到hibernate.cfg.xml的默认new StandardServiceRegistryBuilder().configure()文件。现在,通过这些配置,您应该能够毫无问题地持久保存/加载/更新实体。

我使用Hibernate 4.0对一个快速而脏的示例应用程序测试了此配置。

答案 1 :(得分:0)

只需使用它来构建会话工厂

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

适用于Hibernate 4和Hibernate 5.此代码在Hibernate 4中已弃用,但在Hibernate 5中删除了此弃用。

答案 2 :(得分:0)

配置您的User class喜欢 -

Configuration cfg=new Configuration(); 
cfg.addAnnotatedClass(com.mycompanyname.myapp.User.class);
cfg.configure();
希望它有所帮助。