我试图使用hibernate来使用sqlite。但是,我很难配置sqlite数据库路径。目前,我的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="connection.url">jdbc:sqlite:test.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.test.entity.Category"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
我使用的是IntelliJ。我已将test.db放在资源和资源中。在工件中我可以在类包中看到它。但是,每次我收到此错误:
org.hibernate.hql.internal.ast.QuerySyntaxException: Category is not mapped [select id from Category]
Category.java
@Entity
@Table(name = "category", schema = "", catalog = "")
public class Category {
private String id;
private String name;
private String imageUrl;
@Id
@Column(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "imageUrl")
public String getImageUrl() {
return imageUrl;
}
}
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null){
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
我正在使用Hibernate版本5.1.0
我已经检查了sessionFactory.getAllClassMetadata()
- 它没有显示任何类映射。任何帮助将不胜感激。
答案 0 :(得分:0)
使用不正确的Hibernate 5配置方式。
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
在Hibernate 5中,当你执行configuration.configure("hibernate.cfg.xml")
时,一切都配置正确。但是当你执行configuration.buildSessionFactory(serviceRegistry)
时,所有配置都将丢失。
只做
return new Configuration().configure().buildSessionFactory();
参见
Hibernate 5 :- org.hibernate.MappingException: Unknown entity