测试类
package com.scujcc.ch03;import org.hibernate.*;
import org.hibernate.cfg.*;public class Test { /**
* @param args
*/
public static void main(String[] args) {
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
User user = new User(1,"test","123456","[email protected]"); session.save(user);
tx.commit();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }}JavaBean
package com.scujcc.ch03;public class User {
private int id;
private String username;
private String password;
private String email;
public User(int id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}}
Hibernate映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.scujcc.ch03.User" table="usertable">
<id name="id" column="ID">
<generator class="identity"/>
</id>
<property name="username" column="UserName"></property>
<property name="password" column="Password"></property>
<property name="email" column="Email"></property>
</class>
</hibernate-mapping><?xml version='1.0' encoding='gb2312'?>
<!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.username">sa</property>
<property name="connection.password"></property>
<property name="connection.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=javaee</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect </property>
<property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver </property>
<!--显示SQL语句-->
<property name="show_sql">true</property>
<!-- 数据表对应的映射文件 -->
<mapping resource="com/scujcc/ch03/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>现在插入的数据都是空值?到底为什么
package com.scujcc.ch03;import org.hibernate.*;
import org.hibernate.cfg.*;public class Test { /**
* @param args
*/
public static void main(String[] args) {
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
User user = new User(1,"test","123456","[email protected]"); session.save(user);
tx.commit();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }}JavaBean
package com.scujcc.ch03;public class User {
private int id;
private String username;
private String password;
private String email;
public User(int id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}}
Hibernate映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.scujcc.ch03.User" table="usertable">
<id name="id" column="ID">
<generator class="identity"/>
</id>
<property name="username" column="UserName"></property>
<property name="password" column="Password"></property>
<property name="email" column="Email"></property>
</class>
</hibernate-mapping><?xml version='1.0' encoding='gb2312'?>
<!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.username">sa</property>
<property name="connection.password"></property>
<property name="connection.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=javaee</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect </property>
<property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver </property>
<!--显示SQL语句-->
<property name="show_sql">true</property>
<!-- 数据表对应的映射文件 -->
<mapping resource="com/scujcc/ch03/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>现在插入的数据都是空值?到底为什么
解决方案 »
- ejb3内webservice发布ear包时报org.hibernate.hql.ast.QuerySyntaxException: is not mapped
- jsp 显示本地图片
- 关于struts 2 中s:file 到accept 的用法求解?
- 获取字符数?
- 关于搭建J2EE开发环境的问题(帮顶的都有分啦,火了)
- 页面中的跳转和传值问题
- 用Java的思想写安卓,还是有点问题的
- java中socke连接t默认超时时间
- 刚接触web service ,问一个关于web service做中间层的问题
- 初学EJB,javax.ejb.*; 应该将哪个library 放进来
- Spring AOP测试出现异常:no declaration can be found for element 'aop:aspectj-autoproxy'
- 参数维护
改成class="native"试试
把你控制台的语句贴出来啊!
<property name="connection.password"></property>
没有设置密码 ,设置一下试试
16 INFO [main] org.hibernate.cfg.Environment - hibernate.properties not found
16 INFO [main] org.hibernate.cfg.Environment - using CGLIB reflection optimizer
16 INFO [main] org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
94 INFO [main] org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
94 INFO [main] org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
954 INFO [main] org.hibernate.cfg.Configuration - Reading mappings from resource: com/scujcc/ch03/User.hbm.xml
1063 INFO [main] org.hibernate.cfg.HbmBinder - Mapping class: com.scujcc.ch03.User -> usertable
1079 INFO [main] org.hibernate.cfg.Configuration - Configured SessionFactory: null
1157 INFO [main] org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
1157 INFO [main] org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
1157 INFO [main] org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
1188 INFO [main] org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.microsoft.jdbc.sqlserver.SQLServerDriver at URL: jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=javaee
1188 INFO [main] org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=sa, password=****}
1860 INFO [main] org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server, version: Microsoft SQL Server 2000 - 8.00.2039 (Intel X86)
May 3 2005 23:18:38
Copyright (c) 1988-2003 Microsoft Corporation
Personal Edition on Windows NT 5.1 (Build 2600: Service Pack 3)1860 INFO [main] org.hibernate.cfg.SettingsFactory - JDBC driver: SQLServer, version: 2.2.0040
1907 INFO [main] org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.SQLServerDialect
1907 INFO [main] org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
1907 INFO [main] org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
1907 INFO [main] org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): disabled
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Connection release mode: auto
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
1907 INFO [main] org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
1922 INFO [main] org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Query cache: disabled
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Cache provider: org.hibernate.cache.EhCacheProvider
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Statistics: disabled
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
1922 INFO [main] org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
1969 INFO [main] org.hibernate.impl.SessionFactoryImpl - building session factory
2016 WARN [main] net.sf.ehcache.config.Configurator - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/E:/praxis/Library/hibernate-3.1.2/hibernate-3.1/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
2125 INFO [main] org.hibernate.tuple.PojoInstantiator - no default (no-argument) constructor for class: com.scujcc.ch03.User (class must be instantiated by Interceptor)
2344 INFO [main] org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
Hibernate: insert into usertable (UserName, Password, Email) values (?, ?, ?) select scope_identity()
3063 WARN [main] org.hibernate.util.JDBCExceptionReporter - SQL Error: 515, SQLState: HY000
org.hibernate.exception.GenericJDBCException: could not insert: [com.scujcc.ch03.User]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:91)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:79)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:1986)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2405)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:37)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:243)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:269)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:167)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:559)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:547)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:543)
at com.scujcc.ch03.Test.main(Test.java:19)
Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]无法将 NULL 值插入列 'ID',表 'javaee.dbo.usertable';该列不允许空值。INSERT 失败。
at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processErrorToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRPCRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReply(Unknown Source)
at com.microsoft.jdbc.sqlserver.SQLServerImplStatement.getNextResultType(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonTransitionToState(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.executeInternal(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.execute(Unknown Source)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:1953)
... 15 more
3063 ERROR [main] org.hibernate.util.JDBCExceptionReporter - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]无法将 NULL 值插入列 'ID',表 'javaee.dbo.usertable';该列不允许空值。INSERT 失败。
3063 WARN [main] org.hibernate.util.JDBCExceptionReporter - SQL Error: 3621, SQLState: HY000
3063 ERROR [main] org.hibernate.util.JDBCExceptionReporter - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]语句已终止。
根据log4j的提示是插入了NULL才报错误,正说明了没有插入数据,这就是我奇怪的地方,我也用过set方法传入值,但是仍然是这样,至于改密码和 <generator class="identity"/>
改成class="native"都试过的,我在网上找了好多也解决不了所以才发帖子的,希望高手看出问题来,谢谢
1.将<generator class="identity"/>改为<generator class="assigned"/>
2.如果设置成<generator class="identity"/>,则主键由hibernate自动维护,就不要在程序管主键了
<property name="connection.password"></property> 你沒有設置密碼!!!!!
cfg.configure("配置文件位置如:com/xml/hibernate.cfg.xml")//如果hibernate.cfg.xml不在默认目录src下,在的话可以直接cfg.configure()
2.cfg.addClass(User.class);//根据持久化对象查找映射表确定要操作的数据表SessionFactory factory=cfg.buildSessionFactory();
楼主,对照以上两点查看一下
User user = new User(1,"test","123456","[email protected]");不能指定直,如果要指定,那改成assigned
<id name="id" column="ID">
<generator class="identity"/>
</id>将红色部分改为<generator class="assigned"/>
将<generator class="identity"/>改为
<generator class="assigned"/>