过了好长时间,又拾起hibernate了,好多东西都忘了,错误百出。将出现错误和解决方法记录下。
java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
需要添加两个jar包:slf4j-log4j12-1.5.6.jar、log4j.jar
org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.
需要为数据库连接设置方言,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="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/test</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<mapping resource="orm/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate获得配置的写法
Configuration cfg = new Configuration();
或
Configuration cfg = new Configuration().configure();//这种写法hibernate.cfg.xml文件必须放在src根目录下。
org.hibernate.InvalidMappingException: Could not parse mapping document
解析hbm文件不成功,需要检查hbm文件的配置,其中有些问题需要注意,尽量少用一些可能为关键字的单词做属性名,比如id,一般改成uid、pid之类的。mysql数据库中,id不能作为表的列名,而postgresql可以;postgresql中,user不能作为表名,而mysql可以用作表名。
自动生成*.out.xml文件
比如生成hibernate.cfg.out.xml文件,然后报错,这一般是run xml文件造成的错误,在使用ctrl+F11时,当前编辑器在xml文件上的话,就会出现这样的错误。
使用SchemaExport自动生成库表
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class UserTest {
public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
//cfg.addClass(User.class);
SchemaExport dbExport = new SchemaExport(cfg);
dbExport.create(true, true);
}
}
其中cfg.addClass(User.class);这行,如果hibernate.cfg.xml中配置了<mapping resource="orm/conf/User.hbm.xml"/>,而这行又取消注释了,则会出错,也就是做了重复工作。使用cfg.addClass(User.class)的话,hbm文件就要与实体类在同一目录。
hibernate.dialect' must be set when no Connection available错误
- <span style="color: #ff0000;">org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available </span>
这个问题是比较奇怪的,让人有点郁闷,检查了配置文件,根本没有错,也就说现在问题不是出在这个地方了。而是出现在了其他的地方。网上找了很多,很失望,没有找到正确的。
这个时候得看其他的方面。我出现的问题是
- cfg=new AnnotationConfiguration();
- sf=cfg.buildSessionFactory();
在这里没有写
- cfg=new AnnotationConfiguration().configure();
缺少的是configure();
添加这句话之后程序OK.
new Configuration()默认是读取hibernate.properties
所以使用new Configuration().configure()来读取hibernate.cfg.xml文件