当我尝试将hibernate 5.0与mysql集成时,我收到错误消息org.hibernate.MappingException: Unknown entity
这似乎是hibernate5.0.0和5.0.1的问题。这适用于hibernate 4.3.9
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3307/SampleDB
</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="UserA.User"></mapping>
</session-factory>
package UserA;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Map;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.ServiceRegistry;
public class HibernateMain {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sf = configuration.buildSessionFactory(sr);
User user1 = new User();
user1.setUserName("Arpit");
user1.setUserMessage("Hello world from arpit");
user1.setUserId(22);
Session ss = sf.openSession();
ss.beginTransaction();
// saving objects to session
ss.save(user1);
ss.getTransaction().commit();
ss.close();
}
}
package UserA;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity(name="User_table")
public class User {
@Id
int userId;
@Column(name = "User_Name")
String userName;
@Column(name = "User_Message")
String userMessage;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
答案 0 :(得分:26)
我已经修复了Hibernate 5的相同问题。此代码存在问题
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
SessionFactory sf = configuration.buildSessionFactory(sr);
此代码适用于Hibernate 4.3.5,但相同的代码对Hibernate 5也有相同的问题。
执行configuration.buildSessionFactory(sr)
后,使用Hibernate 5,Configuration
丢失了有关通过调用configuration.configure()
获取的映射的所有信息。
<强>解决方案强>
要解决此问题,如果您使用标准配置文件hibernate.cfg.xml
和hibernate.properties
,则可以通过这种方式创建会话工厂(不使用ServiceRegistry
)
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
加载属性
如果您在hibernate.properties
以外的文件中拥有属性,则可以使用StandardServiceRegistryBuilder
构建会话工厂(无论如何,如果您有hibernate.properties
和其他文件,则会同时加载它们)
将属性作为资源加载
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
configure().loadProperties("hibernate-h2.properties").build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
您需要在类路径(sources文件夹的根目录,资源文件夹)中包含hibernate-h2.properties
。您也可以从根源文件夹指定路径
/com/github/xxx/model/hibernate-h2.properties
。
从文件系统中的路径加载属性
File propertiesPath = new File("some_path");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
configure().loadProperties(propertiesPath).build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
您可以在fluent-hibernate-mysql找到使用此方法的示例控制台应用程序。它使用实用程序类从fluent-hibernate library构建会话工厂。
Hibernate 5教程不正确
Hibernate 5教程1.1.6. Startup and helpers中有一个不正确的示例。它使用此代码
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
它没有做正确的配置。
答案 1 :(得分:6)
在Hibernate 5中,您需要构建StandardServiceRegistry
和Metadata
来构建SessionFactory
。您可以使用以下HibernateUtil
来构建SessionFactory
。 hibernate.cfg.xml
应该位于应用程序的类路径的根目录中。
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
此外,如果你正在使用Hibernate 5并使用@Id
作为你的标识符生成策略,那么使用GenerationType.AUTO
将默认使用MySQL来获取“序列”标识生成器,这将给你一个com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'SampleDB.hibernate_sequence' doesn't exist
例外,如果您没有在标识符属性的实体中配置它。因此,对于Hibernate 5,请改用GenerationType.IDENTITY
。
答案 2 :(得分:0)
您没有添加配置文件
configuration.configure("/hibernate.cfg.xml");
答案 3 :(得分:0)
请确保您已创建映射文件User.hbm.xml或User.xml文件,并将该文件包含在hibernate.cfg.xml中
答案 4 :(得分:0)
使用此:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Session session = sessionFactory.openSession();
而不是:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
解决了Hibernate 5.2.10.Final的问题。
答案 5 :(得分:0)
我面临同样的问题&amp;我搜索了将近2个小时,尝试了不同的方法,例如更换旧的hibernate jar和更改db表架构。但最终得到了如下解决方案;
//This line to be replaced with below commented line
SessionFactory factory = new Configuration().configure().buildSessionFactory();
替换上面的
Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
然后它会正常工作..