hibernate执行保存对象时出现异常:
org.hibernate.exception.GenericJDBCException: could not insert: [com.hibernate.domain.User] Caused by: java.sql.SQLException: Field 'user_id' doesn't have a default value
具体的代码和配置如下:
hibernate.cfg.xml:
<!-- Database connection settings -->
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/hibernate3
root
ytkj
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> -->
<!-- Echo all executed SQL to stdout -->
<!-- show sql dml -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="com/hibernate/domain/User.hbm.xml"/>
</session-factory>
建表语句(成功):
CREATE TABLE t_user
(user_id
int(11) NOT NULL,user_name
varchar(20) default NULL,user_age
int(11) default NULL,
PRIMARY KEY (user_id
)
测试类:
package com.hibernate.manager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.hibernate.domain.User;
import com.hibernate.util.HibernateUtil;
public class UserManager {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction ts = session.beginTransaction();
User user = new User();
user.setId(1);
user.setName("zhangsan");
user.setAge(21);
session.save(user);
ts.commit();
session.close();
sessionFactory.close();
}
User.hbm.xml:
<!-- -->
以上代码执行过后,就包上面的异常。
如果不使用id生成策略(及时没有generator标签),则可以insert成功。
请问这问题是出在哪里?高手指点。
我知道了,是我的建表语句有问题应该是:
CREATE TABLE t_user
(user_id
int(11) NOT NULL auto_increment,user_name
varchar(20) default NULL,user_age
int(11) default NULL,
PRIMARY KEY (user_id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
我少了auto_increment,但是在mysql情况下,少了是会出错的。
因为,这时候的id的生成策略native, id是自动生成的,只要在建表的时候指定为auto_increment即可。
使用hibernate时不应该是自动创建表吗,请问怎么在建表的时候指定为auto_increment的啊
我在配置文件中使用的是 使用的也是native