我制作了一个 Hibernate 配置 maven 项目(使用 maven-shade-plugin 构建),以允许我的代码库使用一个统一的“数据库类”。org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped但是,当从正在运行的项目外部调用时,该类似乎没有映射(在运行时引发异常)。
当在项目中运行时,一切正常。但是,当从项目外部运行时,Hibernate 无法映射实体。
CommonDB.java(maven 包 meta1203-data 的一部分)
package com.meta1203.microservices;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CommonDB <C extends BaseEntity> {
private Configuration cfg;
private SessionFactory sf;
private Session session;
private Class<C> c;
public CommonDB(Class<C> anoClass) {
String jdbcUrl = String.format(
"jdbc:mysql://%s/%s",
System.getenv("DB_URL"),
System.getenv("DB_NAME"));
cfg = new Configuration()
.setProperty("hibernate.connection.url", jdbcUrl)
.setProperty("hibernate.connection.username", System.getenv("DB_USERNAME"))
.setProperty("hibernate.connection.password", System.getenv("DB_PASSWORD"))
.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.pool_size", "1")
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect")
.setProperty("hibernate.hbm2ddl.auto", "update")
.setProperty("hibernate.show_sql", "true")
.addAnnotatedClass(anoClass.getClass());
c = anoClass;
}
public void open() {
sf = cfg.buildSessionFactory();
session = sf.openSession();
}
public void close() {
session.close();
sf.close();
}
public C findOneBy(String field, String o) {
String query = "select u from " + c.getSimpleName() + " u where u." + field + " = :id";
return session.createQuery(query, c).setParameter("id", o).getSingleResult();
}
// other CRUD functions
}
慕标5832272
翻阅古今
慕姐8265434
相关分类