我正在学习hibernate 4,但却被困在 Session Factory 的创建中 并请检查我的代码,并帮助我找出问题的原因,因为我使用的是hibernate-core 5.0.6,MySQL连接器5.0.8,log4j 1.2.17,jta jar,dom4j和jboss-logging jar,这是我的会话工厂代码
class HibernateUtill
{
private static final SessionFactory sessionFactory;
static {
try {
Logger logger = Logger.getLogger("Mylogger");
logger.info("Trying to create a test connection with database");
Configuration configuration = new Configuration().configure();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration
.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Throwable ex) {
System.out.println("SessionFactory creation failed with error" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutDown() {
sessionFactory.close();
}
}
我得到的错误是:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
SessionFactory creation failed with errororg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.commonClasses.HibernateUtil.<clinit>(HibernateUtil.java:19)
at com.java.save.SavingObject.savingObject(SavingObject.java:13)
at com.java.save.SavingObject.main(SavingObject.java:31)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
at com.commonClasses.HibernateUtil.<clinit>(HibernateUtil.java:12)
... 2 more
或简单来说 errororg.hibernate.internal.util.config.ConfigurationException:找不到cfg.xml资源
我知道的是错误是由于log4j而我将log4j.properties放在src文件夹中,而属性文件的代码是
# Root logger option
log4j.rootlogger=INFO,stdout
#Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=trace
请帮我解决此错误并导致此错误。 任何帮助表示赞赏, 感谢。
答案 0 :(得分:2)
您缺少类路径中的hibernate配置文件。这可以命名为ad 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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:3306/hibernatetrial?createDatabaseIfNotExist=true</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="hibernatemapping/mapping.xml"/>
</session-factory>
</hibernate-configuration>
答案 1 :(得分:1)
您需要创建 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.url">jdbc:mysql://localhost:3306/yourDB</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> --> </session-factory> </hibernate-configuration>
将下一个代码添加到 servlet.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
使用下一个代码
创建 .properties 文件database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/yourDB
database.user=user
database.password=password
hibernate.show_sql=true
之后,您可以使用下一个代码
创建hibernate会话Session session = null;
session = sessionFactory.openSession();
String query = "select users.username, users.password, users.name, users.enabled, users.surname, users.email, users.gender, users.age, users.weight, users.height, users.sport, users.place, users.photo from users where users.username LIKE '%s'";
List<Users> userInfoList = session.createSQLQuery(String.format(query, username)).addEntity(Users.class).list();
session.close();
session = null;
答案 2 :(得分:0)
试试这个。
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);