hibernate.cfg.xml 内容如下
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/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://localhost/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">19861210</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>//很明显已经设置了针对MySQL的方言
<property name="hibernate.show_sql">true</property>
<mapping resource="com/bjsxt/hibernate/User.hbm.xml"/>//有一个User类,该类的对象将利用hibernate的功能保存到数据库
</session-factory>
</hibernate-configuration>
java 业务层某个类的代码如下
package com.bjsxt.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Client {
public static void main(String[] args) {
Configuration cfg = new Configuration().addClass(User.class);//注意这条语句
SessionFactory factory = cfg.buildSessionFactory();
Session session = null;
try {
session = factory.openSession();
//开启事务
session.beginTransaction();
User user = new User();
user.setName("张三");
user.setPassword("123");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
//保存数据
session.save(user);
//提交事务
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//关闭session
session.close();
}
}
}
}
}
这样,运行时就出现如下错误:
错误代码:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:378)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:110)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
at org.hibernate.service.BusinessService.<init>(BusinessService.java:15)
at org.hibernate.service.BusinessService.main(BusinessService.java:28)
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.service.BusinessService.sava(BusinessService.java:23)
at org.hibernate.service.BusinessService.main(BusinessService.java:33)
意思是我没有设置数据库方言,可 hibernate.cfg.xml 明明已经设置了,原因何在呢?
原因就在于上面要你注意的红色代码,当我们采用XML文件作为配置文件的时候,定义Configuration对象是不能采用这种形式的,应该改为如下形式:
Configuration cfg=new Configuration().configure();
将该代码改了之后再运行,一切OK。反之,如果你采用properties格式的文件,那么代码就应该不用改动了。建议使用XML文件,比较规范,便于阅读和管理。