一、环境
Oracle 11.2.0 XE
Hibernate4.x
Hibernate.cfg.xml中方言的配置:
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
POJO类:User
package com.ssh.model; public class User { private long id; private String name; private int age; private boolean man; private Group group; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isMan() { return man; } public void setMan(boolean man) { this.man = man; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } }
POJO类User的hbm映射文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.ssh.model"> <class name="User" table="t_user"> <id name="id" type="java.lang.Long" column="u_id"> <!-- <generator class="sequence"> <param name="sequence">user_id_seq</param> </generator> --> <generator class="native"></generator> </id> <property name="name" column="u_name"></property> <property name="age" column="u_age"></property> <property name="man" column="u_man" type="java.lang.Boolean"></property> <many-to-one name="group" column="u_group"></many-to-one> </class> </hibernate-mapping>
测试代码:
package com.ssh.model; import org.hibernate.Session; import org.junit.Test; import com.ssh.model.User; import com.ssh.util.HibernateUtil; public class HibernateTest { @Test public void testSave() { Session session = HibernateUtil.getSession(); session.beginTransaction(); User u = new User(); u.setName("lll"); u.setAge(22); session.save(u); session.getTransaction().commit(); HibernateUtil.closeSession(session); } }
二、问题及解决方法
执行上诉测试代码,抛如下异常:
10:21:35,545 DEBUG SchemaUpdate:226 - create table t_group (g_id number(19,0) not null, g_name varchar2(255), primary key (g_id))
10:21:35,553 DEBUG SchemaUpdate:226 - create table t_user (u_id number(19,0) not null, u_name varchar2(255), u_age number(10,0), u_man boolean, u_group number(19,0), primary key (u_id))
10:21:35,556 ERROR SchemaUpdate:236 - HHH000388: Unsuccessful: create table t_user (u_id number(19,0) not null, u_name varchar2(255), u_age number(10,0), u_man boolean, u_group number(19,0), primary key (u_id))
10:21:35,556 ERROR SchemaUpdate:237 - ORA-00902: 无效数据类型
从上诉的建表语句上看,u_man boolean明显不对,因为oracle是不支持boolean类型的,但是为什么hibernate没有主动做转换为oracle支持的数据类型呢?后来发现就是方言配置的有问题,当前环境下方言应该配置为:<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
从hibernate的官方文档上可以看到:
Oracle 10g and later org.hibernate.dialect.Oracle10gDialect
说明先前的方言已经不适用了。
当然,还有一种解决方法就是你可以不配置方言,这样hibernate会根据driver信息自动为我们这是默认的方言,不过我们不建议这样做。