使用hibernate插入数据的例子

数据库创建脚本:

drop table person create table person( id varchar(32) not null primary key, name varchar(20) not null, password varchar(20) not null, sex varchar(20) , email varchar(30) )

Person类

package org.lz.hibernate; public class Person { //POJO类 private String id; private String name; private String password; private String sex; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }


PersonOperator类:

package org.lz.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class PersonOperator { private Session session = null; public PersonOperator() { Configuration config = new Configuration(); SessionFactory factory = config.configure().buildSessionFactory(); this.session = factory.openSession(); } // 所有的操作都是通过session来完成的 public void PersonInsert(Person p) { Transaction tran = this.session.beginTransaction();//开始事物 this.session.save(p);//执行 tran.commit();//提交 } }

测试方法:

package org.lz.hibernate; public class TestPO { public static void main(String[] args) { Person p = new Person(); p.setId("1"); p.setName("刘召"); p.setPassword("123456"); p.setSex("男"); p.setEmail("123@143.com"); //通过实例化的Person对象插入数据 PersonOperator po = new PersonOperator(); po.PersonInsert(p); } }
配置文件:

person.hbm.xml:

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="org.lz.hibernate.Person" table="PERSON" schema="SCOTT"> <id name="id" type="java.lang.String"> <column name="ID" length="32" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" length="20" not-null="true" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" length="20" not-null="true" /> </property> <property name="sex" type="java.lang.String"> <column name="SEX" length="20" /> </property> <property name="email" type="java.lang.String"> <column name="EMAIL" length="30" /> </property> </class> </hibernate-mapping>
hibernate.cfg.xml:

<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.Oracle9Dialect </property> <property name="connection.url"> jdbc:oracle:thin:@127.0.0.1:1521:ORCL </property> <property name="connection.username">scott</property> <property name="connection.password">tiger</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <property name="myeclipse.connection.profile"> OracleDriver </property> <property name="show_sql">true</property> <mapping resource="org/lz/hibernate/Person.hbm.xml" /> </session-factory> </hibernate-configuration>


展开阅读全文

hibernate 插入数据

01-21

简单的用hibernate中的save()方法向表中插入一条数据,数据4个字段,其中id为自增长,workname字段是我从表单获取过来的内容,其他两个str1,str2库中设置可为空,所以暂时不添加,这个save()方法我怎么用都写不对,尤其Id这里,我写上setId()就报错:不能添加显性数据什么的,不写的话又提示null字段错误,很郁闷,原来做的都是读取今天做个添加怎么都写不出来,帮帮忙大家:rnaction代码:rn[code=Java]rnpublic class Addwork extends Action rn public ActionForward execute (ActionMapping mapping,ActionForm form,rn HttpServletRequest request,HttpServletResponse response)rn rn tryrn request.setCharacterEncoding("gb2312");rn String workname = request.getParameter("workname");rn rn if(!workname.equals("") && !workname.isEmpty())rn rn List temp = new WorkNameDAO().findbyname(workname);rn if(temp.size()>=1)rn rn return mapping.findForward("err");rn rn elsern rn rn /*SaveForm saveForm = (SaveForm) form;rn Transaction tx=WorkNameDAO.getSessionFactory().openSession().beginTransaction(); rn WorkName article=new WorkName();rn article.setTitle(saveForm.getTitle());rn article.setContent(saveForm.getContext());rn WorkNameDAO.save(article);rn tx.commit();rn return mapping.findForward("success");*/rnrn rn rn rn HibernateSessionFactory.getSessionFactory().openSession();rn WorkName wkname = new WorkName();rn wkname.setWorkname(workname);rn wkname.setBewrite("");rn wkname.setWkprincipal("");rn WorkNameDAO um = new WorkNameDAO();rn um.save(wkname);rn HibernateSessionFactory.getSessionFactory().close();rn return mapping.findForward("addsecc"); rn rn rn elsern return mapping.findForward("err");rn rn catch(UnsupportedEncodingException e)rn return mapping.findForward("logonerr");rn rn rn[/code]rnMyEclipse自动生成的DAO文件代码:rn[code=Java]public void save(WorkName transientInstance) rn log.debug("saving WorkName instance");rn try rn getSession().save(transientInstance);rn log.debug("save successful");rn catch (RuntimeException re) rn log.error("save failed", re);rn throw re;rn rn [/code] 论坛

hibernate插入数据没有反应

03-23

郁闷的我头疼,我实在搞不明白为什么了,我手动给good设置值之后,调用DAO层的create方法,插入数据库,控制台不提示错误,也显示了执行的SQL语句,可是数据库中没有数据!我手动往数据库中添加数据库,然后调用find方法,查到,而且一个一个的输出每个属性,也有值,可是为什么插入数据就不行呢?还有更新!我又建了一个TYPE类,可以插入!高手请指点一下小弟!感激不尽rn@Entityrn@Table(name = "tb_good")rnpublic class Good rn @Idrn @GeneratedValue(strategy = GenerationType.AUTO)rn private Integer id;rnrn @ManyToOne(cascade = CascadeType.PERSIST , fetch = FetchType.EAGER)rn @JoinColumn(name = "type_id")rn rn private GoodType goodType;rn private String name;rn private String code;rn private Integer num;rn private String XingHao;rn private Double price;rn private String picUrl;rn rn @Column(columnDefinition = "text")rn private String describe;rn private Integer isNew;rn rn @Temporal(value = TemporalType.DATE)rn private Date addNew;rn (省略get,set方法)rnrnrn[img=http://hi.csdn.net/attachment/201103/23/2426554_1300871436ZjO2.gif][/img]rnrnpublic void create(T object) rnrn Session session = HibernateSessionFactory.getSessionFactory()rn .openSession();rnrn try rn session.beginTransaction();rnrn session.persist(object);rnrn session.getTransaction().commit();rnrn catch (Exception e) rn session.getTransaction().rollback();rn finally rn session.close();rn rn rn 论坛

org.hibernate.exception.ConstraintViolationException hibernate插入数据的问题

12-02

我调用getHibernateTemplate().save(o);这个方法的时候抛了如下的异常~!rnrn2008-12-01 23:40:38,671 [org.hibernate.util.JDBCExceptionReporter]-[WARN] SQL Error: 515, SQLState: 23000rn2008-12-01 23:40:38,671 [org.hibernate.util.JDBCExceptionReporter]-[ERROR] 不能将值 NULL 插入列 'cust_no',表 'jb_crm_team0.dbo.cst_customer';列不允许有空值。INSERT 失败。rn2008-12-01 23:40:38,671 [org.apache.struts.action.RequestProcessor]-[WARN] Unhandled Exception thrown: class org.springframework.dao.DataIntegrityViolationExceptionrn2008-12-01 23:40:38,703 [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/CRM].[action]]-[ERROR] Servletaction的Servlet.service()发生意外(exception)rnorg.hibernate.exception.ConstraintViolationException: could not insert: [org.alex.work.entity.CstCustomer]rn at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)rn at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)rn at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)rn at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)rn at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)rn at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)rn at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)rn at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)rn at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)rn at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)rn at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)rn at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)rn at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)rn at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)rn at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)rn at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)rn at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)rn at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)rn at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:635)rn at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:372)rn at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:632)rn at org.alex.common.dao.hibimpl.CommonDAOHibImpl.add(CommonDAOHibImpl.java:27)rn at org.alex.work.biz.ChanceBiz.setCustAndLink(ChanceBiz.java:174)rn at org.alex.work.biz.ChanceBiz$$FastClassByCGLIB$$91d41ead.invoke()rn at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)rn at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:695)rn at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:139)rn at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)rn at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161)rn at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:630)rn at org.alex.work.biz.ChanceBiz$$EnhancerByCGLIB$$4fe82591.setCustAndLink()rn at org.alex.work.web.action.PlanAction.doSuc(PlanAction.java:151)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rn at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274)rn at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194)rn at org.alex.common.web.action.BaseAction.execute(BaseAction.java:46)rn at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)rn at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)rn at org.alex.common.filter.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:93)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)rn at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)rn at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)rn at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)rn at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)rn at java.lang.Thread.run(Unknown Source)rnCaused by: com.microsoft.sqlserver.jdbc.SQLServerException: 不能将值 NULL 插入列 'cust_no',表 'jb_crm_team0.dbo.cst_customer';列不允许有空值。INSERT 失败。rn at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(Unknown Source)rn at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source)rn at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(Unknown Source)rn at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)rn at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)rn ... 60 morern我在调试的时候用get把这个值给输出来了可最后还是抛这个异常,还望高手能够能告知可能是哪些地方弄错了,小弟在这里谢谢了~!rn 论坛

Hibernate插入数据时报错!

09-21

使用Access作数据库(知道它很差,但是方案定了,无奈...)rnID使用AutoIncrecement(counter),就是自动编号rn在插入数据时报错,在外面直接插入时没有问题rn1。配置文件中ID用rn generator class="identity" 或 generator class="native"rn 出错信息:rn Hibernate: insert into teacher (paperID, course, grade, name, notes, operateCustom,passwd, permitItem, permitPaper, teachClass) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) select scope_identity()rnJDBCExceptionReporter - [Microsoft][ODBC Microsoft Access Driver] SQL 语句的结束位置缺少分号 (;)。rnorg.hibernate.exception.SQLGrammarException: could not insert: [com.maystar.model.Teacher]rnrn ... ...rn2。配置文件中如果自己写sqlrn nsert into teacher (paperID, course, grade, name, notes, operateCustom, passwd, permitItem, permitPaper, teachClass) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)rn 出错信息:rn root cause rnrnjava.lang.NullPointerExceptionrn org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:1755)rn org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:2178)rn org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:34)rn org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)rn org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:240)rn org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:160)rn org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:95)rn org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)rn org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)rn org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)rn org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)rn org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)rn org.hibernate.impl.SessionImpl.save(SessionImpl.java:481)rn org.hibernate.impl.SessionImpl.save(SessionImpl.java:476)rn test.student.BaseDAO.createObj(BaseDAO.java:21)rn test.struts.StuAction.insert(StuAction.java:27)rn sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn java.lang.reflect.Method.invoke(Method.java:324)rn org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274)rn org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194)rn org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)rn org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)rn org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)rn org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:763)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:856)rnrnrn各位大侠帮帮忙吧!郁闷好久了。rn 论坛

hibernate插入数据错误!

02-29

第一次写hibernate 一个简单的插入数据代码 rn数据库为mysql 表格名stu 列 username varchar primary key,password varcharrn持久化类 reg rn对应的xml reg.hbm.xmlrnrnrnrnrn rn rn rn rn rn rnrnrnhibernate.cfg.xmlrnrnrnrnrnrn rn rootrn jdbc:mysql://localhost:3306/studentrn org.hibernate.dialect.MySQLDialectrn com.mysql.jdbc.Driverrn rootrn com.mysql.jdbc.Driverrn rn rnrnrn代码运行后rnrnjavax.servlet.ServletException: could not insert: [HPO.reg]rn org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:523)rn org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421)rn org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)rn org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)rn org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:709)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:802)rnrnrnroot cause rnrnorg.hibernate.exception.GenericJDBCException: could not insert: [HPO.reg]rn org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)rn org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)rn org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)rn org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:1986)rn org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2405)rn org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:37)rn org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)rn org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:269)rn org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:167)rn org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101)rn org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)rn org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)rn org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)rn org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)rn org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)rn org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:530)rn org.hibernate.impl.SessionImpl.save(SessionImpl.java:518)rn org.hibernate.impl.SessionImpl.save(SessionImpl.java:514)rn com.yourcompany.struts.action.RegAction.execute(RegAction.java:34)rn org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)rn org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)rn org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)rn org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:709)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:802)rnrnrn清高手指点 郁闷一个晚上了 谢谢rn 论坛

hibernate 一对多插入数据失败

11-21

当我运行我的代码时.只能向主表里面插入数据.面子表是空的..这是怎么回事.请帮一下...rn运行结束如:rnrnHibernate: insert into Customer (custName, CID) values (?, ?)rnHibernate: update Account set ACCNUMBER=?, CIDFORCUSTOMER=? where AID=?rnHibernate: update Account set ACCNUMBER=?, CIDFORCUSTOMER=? where AID=?rnrn本应是三个插入语句 的.现在有两条更新的语句,不得解,请求帮助.....rn//========================================================================rn以下是代码:rnCustomer.hbm.xml文件:rnrnrnrnrnrn rn rn rn rn rn rn rn rn rn rn rnrnrnAccount.hbm.xml文件:rnrnrnrnrn rn rn rn rn rn rn rn rn rn rn rn rnrn//===========================================rnAccount class 文件:rnpackage com.hibernate;rnrnimport java.io.Serializable;rnrnpublic class Account implements Serializable rnrn private static final long serialVersionUID =1l;rn private Integer aid;rn private String accNumber;rn private Customer customer;rn public String getAccNumber() rn return accNumber;rn rn public void setAccNumber(String accNumber) rn this.accNumber = accNumber;rn rn public Integer getAid() rn return aid;rn rn public void setAid(Integer aid) rn this.aid = aid;rn rn public Customer getCustomer() rn return customer;rn rn public void setCustomer(Customer customer) rn this.customer = customer;rn rnrnrn//================================rnCustomer class 文件:rnpackage com.hibernate;rnrnimport java.io.Serializable;rnimport java.util.HashSet;rnimport java.util.Set;rnrnpublic class Customer implements Serializable rnrn private static final long serialVersionUID =1l;rnprivate String custId;rn private String custName;rn private Set accounts=new HashSet();rn public Customer()rn rn rn rn public Set getAccounts() rn return accounts;rn rn public void setAccounts(Set accounts) rn this.accounts = accounts;rn rn rn public String getCustName() rn return custName;rn rn public void setCustName(String custName) rn this.custName = custName;rn rn public String getCustId() rn return custId;rn rn public void setCustId(String custId) rn this.custId = custId;rn rn rnrnrn//==================================================================rn测试文件rn/**rn * rn */rnpackage com.hibernate;rnrnimport org.hibernate.Session;rnimport org.hibernate.SessionFactory;rnimport org.hibernate.Transaction;rnimport org.hibernate.cfg.Configuration;rnrn/**rn * @author lirn *rn */rnpublic class Test rnrn /**rn * @param argsrn */rn public static void main(String[] args) rn // TODO Auto-generated method stubrn Configuration conf=new Configuration();rn conf.configure();rn SessionFactory sf=conf.buildSessionFactory();rn Customer cust=new Customer();rn cust.setCustId("Ca05f");rn cust.setCustName("liqinqin");rn rn Session s=sf.openSession();rn Transaction tx=s.beginTransaction();rn rn rn Account acc=new Account();rn acc.setAid(003);rn acc.setAccNumber("C00100001");rn acc.setCustomer(cust);rn cust.getAccounts().add(acc);rn rn Account acc1=new Account();rn acc1.setAid(004);rn acc1.setAccNumber("C00100001");rn acc1.setCustomer(cust);rn rn //cust.setAccounts( ());rn rn cust.getAccounts().add(acc1);rn rn s.save(cust);rn rn s.flush();rn tx.commit();rn s.close();rn sf.close();rn rn rnrnrn 论坛

求教,Hibernate插入数据的问题

07-07

想往数据库里插数据,写了个bean配完hibernate.cfg.xml和hbm.xml后测试了下,一排错误,心都碎了。。。rn求各位大侠帮小弟我找找哪里出了错,感激不尽啊rnrn-----------------------------------------------------------------------------------rnrnJavaBean-->User-->里面有id,username和password 内容我就复制了,就是些get和set方法rn-----------------------------------------------------------------------------------rnUser.hbm.xmlrnrnrnrnrn rn rn rn rn rn rn rn rn rn rn rnrn-----------------------------------------------------------------------------------rn测试类TestUrnrnpackage test;rnrnimport org.hibernate.Session;rnimport org.hibernate.SessionFactory;rnimport org.hibernate.Transaction;rnimport org.hibernate.cfg.Configuration;rnimport org.junit.Test;rnrnimport pojo.User;rnrnpublic class TestUrn @Testrn public void Add()rn Configuration configuration=new Configuration().configure();rn SessionFactory factory=configuration.buildSessionFactory();rn Session session=factory.openSession();rn Transaction tx=session.beginTransaction();rn User u=new User();rn u.setUsername("kasijia");rn u.setPassword("1985119");rn session.save(u);rn tx.commit();rn rnrnrn-----------------------------------------------------------------------------------rnorg.hibernate.exception.SQLGrammarException: could not insert: [pojo.User]rn at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)rn at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)rn at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)rn at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)rn at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)rn at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)rn at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)rn at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)rn at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)rn at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)rn at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)rn at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)rn at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)rn at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)rn at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)rn at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)rn at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)rn at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)rn at test.TestU.Add(TestU.java:21)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rn at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)rn at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)rn at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)rn at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)rn at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)rn at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66)rn at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)rn at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)rn at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)rn at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)rn at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)rn at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)rnCaused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'boyue.hao' doesn't existrn at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)rn at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)rn at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)rn at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)rn at com.mysql.jdbc.Connection.execSQL(Connection.java:3256)rn at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1313)rn at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1585)rn at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1500)rn at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1485)rn at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)rn at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)rn ... 36 morern 论坛

Hibernate插入数据出错

06-30

下面是报错信息:rn---------------------------------------------------------------------------------- rn2006-06-30 02:16:02,015 DEBUG (Printer.java:83) - listing entities:rn 2006-06-30 02:16:02,015 DEBUG (Printer.java:90) - test.model.businessobject.CategorycategoryName=asdasd, remark=asdasdasd, categoryId=47rn 2006-06-30 02:16:02,015 DEBUG (AbstractFlushingEventListener.java:289) - executing flushrn 2006-06-30 02:16:02,015 DEBUG (AbstractEntityPersister.java:2034) - Inserting entity: [test.model.businessobject.Category#47]rn 2006-06-30 02:16:02,015 DEBUG (AbstractBatcher.java:311) - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)rn 2006-06-30 02:16:02,015 DEBUG (AbstractBatcher.java:346) - insert into TEST.CATEGORY (CATEGORYNAME, REMARK, CATEGORYID) values (?, ?, ?)rn Hibernate: insert into TEST.CATEGORY (CATEGORYNAME, REMARK, CATEGORYID) values (?, ?, ?)rn2006-06-30 02:16:02,031 DEBUG (AbstractBatcher.java:424) - preparing statementrn 2006-06-30 02:16:02,031 DEBUG (AbstractEntityPersister.java:1821) - Dehydrating entity: [test.model.businessobject.Category#47]rn 2006-06-30 02:16:02,031 DEBUG (NullableType.java:79) - binding 'asdasd' to parameter: 1rn 2006-06-30 02:16:02,031 DEBUG (NullableType.java:79) - binding 'asdasdasd' to parameter: 2rn 2006-06-30 02:16:02,031 DEBUG (NullableType.java:79) - binding '47' to parameter: 3rn 2006-06-30 02:16:02,031 DEBUG (BatchingBatcher.java:28) - Adding to batchrn 2006-06-30 02:16:02,031 DEBUG (BatchingBatcher.java:55) - Executing batch size: 1rn 2006-06-30 02:16:02,046 DEBUG (BatchingBatcher.java:85) - success of batch update unknown: 0rn 2006-06-30 02:16:02,046 DEBUG (AbstractBatcher.java:319) - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)rn 2006-06-30 02:16:02,046 DEBUG (AbstractBatcher.java:470) - closing statementrn 2006-06-30 02:16:02,046 DEBUG (AbstractFlushingEventListener.java:316) - post flushrn 2006-06-30 02:16:02,046 DEBUG (SessionFactoryUtils.java:770) - Closing Hibernate Sessionrn 2006-06-30 02:16:02,046 DEBUG (SessionImpl.java:292) - closing sessionrn 2006-06-30 02:16:02,046 DEBUG (ConnectionManager.java:281) - performing cleanuprn 2006-06-30 02:16:02,046 DEBUG (ConnectionManager.java:342) - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]rn 2006-06-30 02:16:02,062 DEBUG (DriverManagerConnectionProvider.java:129) - returning connection to pool, pool size: 1rn 2006-06-30 02:16:02,062 DEBUG (JDBCContext.java:197) - after transaction completionrn 2006-06-30 02:16:02,062 DEBUG (ConnectionManager.java:205) - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!rn 2006-06-30 02:16:02,062 DEBUG (SessionImpl.java:440) - after transaction completionrn java.lang.ClassCastException: java.lang.Integerrn at test.model.dao.impl.CategoryDao.saveCategory(CategoryDao.java:23)rn at test.model.service.impl.CategoryServiceImpl.saveCategory(CategoryServiceImpl.java:34)rn ....rnrnrn-------------------------------rnhbm文件中categoryId的配置是rn rn rn rn SEQ_CATEGORYrn rn rnrnrn--------------------rnCategory类的categoryId属性是int,我改为Integer还是报错rnrnrn请各位帮忙解答!!! 论坛

hibernate +spring插入数据的问题

09-19

表结构:rnid (auto_increment),name,password,address,email,telephonern=========rn配置文件rnrn rn rn rn rn rn rn rn rn rn================================rnrnhibernateDAO:rnpublic User saveUser(User user) rn try rnrn this.getHibernateTemplate().save(user);rn LOGGER.debug("保存用户信息到数据库成功!");rn return user;rn catch (Exception ex) rn LOGGER.error("保存用户信息到数据库失败!");rn ex.printStackTrace();rn return null;rn rn rn=============================rnserviceDAO:rnpublic User saveUser(User user) rn return this.getUserDAO().saveUser(user);rn rn==========================rn测试代码:rnrnpublic void testUser() rn UserService us = (UserService) AppContext.getInstance().getAppContext()rn .getBean("userService");rn User user = new User();rn rn user.setName("W");rn System.out.println(user.getName());rn user.setPassword("Q");rn System.out.println(user.getPassword());rn user.setAddress("QQQ");rn System.out.println(user.getAddress());rn user.setEmail("Q");rn System.out.println(user.getEmail());rn user.setTelephone(111);rn System.out.println(user.getTelephone());rn User uu = us.saveUser(user);rn System.out.println(uu.getId());rn==========================================rnorg.springframework.jdbc.BadSqlGrammarException: Bad SQL grammar [] in task 'Hibernate operation'; nested exception is java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"users"' at line 1rnjava.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to usernrn===========rn大家帮忙看看啊!!!!! 论坛

hibernate插入数据时报错

08-13

hibernate配置文件rn[code=Java]rnrn rn rn rn rn rn rn rn rn rn rn rn[/code]rnrnMonitoredObj类rn[code=Java]rnpublic class MonitoredObjrnrn private String name;rnrn private String group;rnrn private String descri;rnrn[/code]rnrn表结构:rn[code=SQL]rnCREATE TABLE `CIA_MONITORED_OBJ` (rn `name` varchar(50) NOT NULL,rn `descri` varchar(200) NOT NULL,rn `group` varchar(50) NOT NULL,rn PRIMARY KEY (`name`)rn) rn[/code]rnrn测试rnrnpublic void testSave()rn MonitoredObj monitoredObj=new MonitoredObj();rn monitoredObj.setName("Obj1");rn monitoredObj.setDescri("first Obj");rn monitoredObj.setGroup("Obj");rn monitoredObjDao.save(monitoredObj);rnrn rnrn在插入数据的时候报了以下错误信息:rnrnHibernate: insert into CIA_MONITORED_OBJ (descri, group, name) values (?, ?, ?)rn2010-08-13 09:27:02,671 [org.hibernate.util.JDBCExceptionReporter]-[WARN] SQL Error: 1064, SQLState: 42000rn2010-08-13 09:27:02,671 [org.hibernate.util.JDBCExceptionReporter]-[ERROR] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, name) values ('first Obj', 'Obj', 'Obj1')' at line 1rn2010-08-13 09:27:02,671 [org.hibernate.event.def.AbstractFlushingEventListener]-[ERROR] Could not synchronize database state with sessionrnorg.hibernate.exception.SQLGrammarException: Could not execute JDBC batch updatern at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:70)rn at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)rn at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:181)rn at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:226)rn at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:136)rn at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)rn at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)rn at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:730)rn at com.spring.test.BaseTester.tearDown(BaseTester.java:32)rn at junit.framework.TestCase.runBare(TestCase.java:140)rn at junit.framework.TestResult$1.protect(TestResult.java:110)rn at junit.framework.TestResult.runProtected(TestResult.java:128)rn at junit.framework.TestResult.run(TestResult.java:113)rn at junit.framework.TestCase.run(TestCase.java:124)rn at junit.framework.TestSuite.runTest(TestSuite.java:232)rn at junit.framework.TestSuite.run(TestSuite.java:227)rn at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:76)rn at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)rn at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)rnCaused by: java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, name) values ('first Obj', 'Obj', 'Obj1')' at line 1rn at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1237)rn at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:936)rn at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)rn at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:57)rn at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:174)rn ... 20 morernorg.hibernate.exception.SQLGrammarException: Could not execute JDBC batch updatern at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:70)rn at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)rn at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:181)rn at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:226)rn at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:136)rn at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)rn at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)rn at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:730)rn at com.spring.test.BaseTester.tearDown(BaseTester.java:32)rn at junit.framework.TestCase.runBare(TestCase.java:140)rn at junit.framework.TestResult$1.protect(TestResult.java:110)rn at junit.framework.TestResult.runProtected(TestResult.java:128)rn at junit.framework.TestResult.run(TestResult.java:113)rn at junit.framework.TestCase.run(TestCase.java:124)rn at junit.framework.TestSuite.runTest(TestSuite.java:232)rn at junit.framework.TestSuite.run(TestSuite.java:227)rn at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:76)rn at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)rn at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)rnCaused by: java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, name) values ('first Obj', 'Obj', 'Obj1')' at line 1rn at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1237)rn at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:936)rn at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)rn at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:57)rn at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:174)rn ... 20 morernrn大家帮忙看看。rnrnrn 论坛

没有更多推荐了,返回首页