Hello everbody,
I have a problem in inserting data in database using hibernate, Lets i explain total scenario of my problem,
I creates three tables in mysql database.
1) Category: which has following fields.
-cid (int 6)(primary key,) -cname (varchar 100) (NULL) -description (varchar 100) (NULL) -parentid (int 6) (NULL)
2)Test: which has following fields.
-tid (int 6) (primary key,) -tname (varchar 100) (NULL) -criteria (varchar 100) (NULL) -cid (int 6) (references Category(cid)) (NULL)
3)Question: which has following fields.
-id (int 6) (primary key,) -qid (int 6) (NULL) -question (varchar 100) (NULL) -option (varchar 100) -answer (int 1) -tid (int 6) (references Test(tid)) (NULL) -cid (int 6) (references Category(cid))
I am using NetBeans 6.8 IDE and tomacat server. I ceates java web application with hibernate. first i creates reverse engineering and then creates "Hibernate mapping files and POJOs from database"
please make one java package named as "pojos" and creates all pojos and hbm files in that package.
below is all pojo and hbm files..........
1)category.hbm.xml :-
<?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="pojos.Category" table="category" catalog="test"> <id name="cid" type="java.lang.Integer"> <column name="cid" /> <generator class="identity" /> </id> <property name="cname" type="string"> <column name="cname" length="100" /> </property> <property name="description" type="string"> <column name="description" length="100" /> </property> <property name="parentid" type="java.lang.Integer"> <column name="parentid" /> </property> <set name="questions" inverse="true"> <key> <column name="cid" /> </key> <one-to-many class="pojos.Question" /> </set> <set name="tests" inverse="true"> <key> <column name="cid" /> </key> <one-to-many class="pojos.Test" /> </set> </class> </hibernate-mapping>
---------------------------------------------------------------------------------------
2) test.hbm.xml:-
<?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="pojos.Test" table="test" catalog="test"> <id name="tid" type="java.lang.Integer"> <column name="tid" /> <generator class="identity" /> </id> <many-to-one name="category" class="pojos.Category" fetch="select"> <column name="cid" /> </many-to-one> <property name="tname" type="string"> <column name="tname" length="100" /> </property> <property name="criteria" type="string"> <column name="criteria" length="100" /> </property> <set name="questions" inverse="true"> <key> <column name="tid" /> </key> <one-to-many class="pojos.Question" /> </set> </class> </hibernate-mapping>
--------------------------------------------------------------------------------------
3) question.hbm.xml :-
<?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="pojos.Question" table="question" catalog="test"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="identity" /> </id> <many-to-one name="test" class="pojos.Test" fetch="select"> <column name="tid" /> </many-to-one> <many-to-one name="category" class="pojos.Category" fetch="select"> <column name="cid" /> </many-to-one> <property name="qid" type="java.lang.Integer"> <column name="qid" /> </property> <property name="question" type="string"> <column name="question" length="100" /> </property> <property name="option" type="string"> <column name="option" length="100" /> </property> <property name="answer" type="java.lang.Integer"> <column name="answer" /> </property> </class> </hibernate-mapping>
-----------------------------------------------------------------------------------------
Below is all POJO files.....
1) Category.java :-
package pojos;
import java.util.HashSet; import java.util.Set;
public class Category implements java.io.Serializable { private Integer cid; private String cname; private String description; private Integer parentid; private Set<Question> questions = new HashSet<Question>(0); private Set<Test> tests = new HashSet<Test>(0);
public Category() { }
public Category(String cname, String description, Integer parentid, Set<Question> questions, Set<Test> tests) { this.cname = cname; this.description = description; this.parentid = parentid; this.questions = questions; this.tests = tests; } public Integer getCid() { return this.cid; } public void setCid(Integer cid) { this.cid = cid; } public String getCname() { return this.cname; } public void setCname(String cname) { this.cname = cname; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public Integer getParentid() { return this.parentid; } public void setParentid(Integer parentid) { this.parentid = parentid; } public Set<Question> getQuestions() { return this.questions; } public void setQuestions(Set<Question> questions) { this.questions = questions; } public Set<Test> getTests() { return this.tests; } public void setTests(Set<Test> tests) { this.tests = tests; } }
----------------------------------------------------------------------------------------
2) Test.java :-
package pojos;
import java.util.HashSet; import java.util.Set;
public class Test implements java.io.Serializable { private Integer tid; private Category category; private String tname; private String criteria; private Set<Question> questions = new HashSet<Question>(0);
public Test() { }
public Test(Category category, String tname, String criteria, Set<Question> questions) { this.category = category; this.tname = tname; this.criteria = criteria; this.questions = questions; } public Integer getTid() { return this.tid; } public void setTid(Integer tid) { this.tid = tid; } public Category getCategory() { return this.category; } public void setCategory(Category category) { this.category = category; } public String getTname() { return this.tname; } public void setTname(String tname) { this.tname = tname; } public String getCriteria() { return this.criteria; } public void setCriteria(String criteria) { this.criteria = criteria; } public Set<Question> getQuestions() { return this.questions; } public void setQuestions(Set<Question> questions) { this.questions = questions; } }
-----------------------------------------------------------------------------------------
3) Question.java :-
package pojos;
public class Question implements java.io.Serializable { private Integer id; private Test test; private Category category; private Integer qid; private String question; private String option; private Integer answer;
public Question() { }
public Question(Test test, Category category, Integer qid, String question, String option, Integer answer) { this.test = test; this.category = category; this.qid = qid; this.question = question; this.option = option; this.answer = answer; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Test getTest() { return this.test; } public void setTest(Test test) { this.test = test; } public Category getCategory() { return this.category; } public void setCategory(Category category) { this.category = category; } public Integer getQid() { return this.qid; } public void setQid(Integer qid) { this.qid = qid; } public String getQuestion() { return this.question; } public void setQuestion(String question) { this.question = question; } public String getOption() { return this.option; } public void setOption(String option) { this.option = option; } public Integer getAnswer() { return this.answer; } public void setAnswer(Integer answer) { this.answer = answer; } }
----------------------------------------------------------------------------------------
now I created one package named as "servlets" and make one servlet as "addQuestionData".
below is that servlet "addQuestionData.java" :-
package servlets;
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import pojos.Category; import pojos.Question; import pojos.Test;
public class addQuestion extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {
SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); Transaction tx = s.beginTransaction();
Category c = new Category(); c.setCname("gate-2011"); c.setDescription("Entrence for MTech."); c.setParentid(0);
s.save(c); tx.commit();
out.print("Category Data saved.<br/>");
Test t = new Test(); t.setTname("Test1"); t.setCriteria("20:2:1;"); t.setCategory(c);
tx.begin(); s.save(t); tx.commit();
out.print("Test Data saved.<br/>");
Question q = new Question(); q.setQid(1); q.setQuestion("name"); q.setOption("jayesh:pratik:priyanka:pruthika;"); q.setAnswer(1); q.setTest(t); q.setCategory(c);
tx.begin(); s.save(q); tx.commit(); s.close(); out.print("Question Data saved."); }catch(Exception ex){ ex.printStackTrace(); } finally { out.close(); } }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
/** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
/** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
----------------------------------------------------------------------------------------
After run the servlet , it will insert data in category and test table, but it will not insert data in to question table, i got this error :-
-----------------------------------------------------------------------------------------
Mar 30, 2011 2:27:16 PM org.hibernate.cfg.Environment <clinit> INFO: Hibernate 3.2.5 Mar 30, 2011 2:27:16 PM org.hibernate.cfg.Environment <clinit> INFO: hibernate.properties not found Mar 30, 2011 2:27:16 PM org.hibernate.cfg.Environment buildBytecodeProvider INFO: Bytecode provider name : cglib Mar 30, 2011 2:27:16 PM org.hibernate.cfg.Environment <clinit> INFO: using JDK 1.4 java.sql.Timestamp handling Mar 30, 2011 2:27:17 PM org.hibernate.cfg.Configuration configure INFO: configuring from resource: /hibernate.cfg.xml Mar 30, 2011 2:27:17 PM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: Configuration resource: /hibernate.cfg.xml Mar 30, 2011 2:27:17 PM org.hibernate.cfg.Configuration addResource INFO: Reading mappings from resource : pojos/Question.hbm.xml Mar 30, 2011 2:27:17 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues INFO: Mapping class: pojos.Question -> question Mar 30, 2011 2:27:18 PM org.hibernate.cfg.Configuration addResource INFO: Reading mappings from resource : pojos/Category.hbm.xml Mar 30, 2011 2:27:18 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues INFO: Mapping class: pojos.Category -> category Mar 30, 2011 2:27:18 PM org.hibernate.cfg.Configuration addResource INFO: Reading mappings from resource : pojos/Test.hbm.xml Mar 30, 2011 2:27:18 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues INFO: Mapping class: pojos.Test -> test Mar 30, 2011 2:27:18 PM org.hibernate.cfg.Configuration doConfigure INFO: Configured SessionFactory: null Mar 30, 2011 2:27:18 PM org.hibernate.cfg.HbmBinder bindCollectionSecondPass INFO: Mapping collection: pojos.Category.questions -> question Mar 30, 2011 2:27:18 PM org.hibernate.cfg.HbmBinder bindCollectionSecondPass INFO: Mapping collection: pojos.Category.tests -> test Mar 30, 2011 2:27:18 PM org.hibernate.cfg.HbmBinder bindCollectionSecondPass INFO: Mapping collection: pojos.Test.questions -> question Mar 30, 2011 2:27:18 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Using Hibernate built-in connection pool (not for production use!) Mar 30, 2011 2:27:18 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Hibernate connection pool size: 20 Mar 30, 2011 2:27:18 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: autocommit mode: false Mar 30, 2011 2:27:18 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/test Mar 30, 2011 2:27:18 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: connection properties: {user=root} Mar 30, 2011 2:27:20 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: RDBMS: MySQL, version: 5.0.51b-community-nt Mar 30, 2011 2:27:20 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} ) Mar 30, 2011 2:27:20 PM org.hibernate.dialect.Dialect <init> INFO: Using dialect: org.hibernate.dialect.MySQLDialect Mar 30, 2011 2:27:20 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory INFO: Using default transaction strategy (direct JDBC transactions) Mar 30, 2011 2:27:20 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) Mar 30, 2011 2:27:20 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Automatic flush during beforeCompletion(): disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Automatic session close at end of transaction: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC batch size: 15 Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC batch updates for versioned data: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Scrollable result sets: enabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC3 getGeneratedKeys(): enabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Connection release mode: auto Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Maximum outer join fetch depth: 2 Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Default batch fetch size: 1 Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Generate SQL with comments: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Order SQL updates by primary key: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Order SQL inserts for batching: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory Mar 30, 2011 2:27:21 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init> INFO: Using ASTQueryTranslatorFactory Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Query language substitutions: {} Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: JPA-QL strict compliance: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Second-level cache: enabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Query cache: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory createCacheProvider INFO: Cache provider: org.hibernate.cache.NoCacheProvider Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Optimize cache for minimal puts: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Structured second-level cache entries: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Statistics: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Deleted entity synthetic identifier rollback: disabled Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Default entity-mode: pojo Mar 30, 2011 2:27:21 PM org.hibernate.cfg.SettingsFactory buildSettings INFO: Named query checking : enabled Mar 30, 2011 2:27:21 PM org.hibernate.impl.SessionFactoryImpl <init> INFO: building session factory Mar 30, 2011 2:27:23 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance INFO: Not binding factory to JNDI, no JNDI name configured org.hibernate.exception.SQLGrammarException: could not insert: [pojos.Question] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) 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:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at servlets.addQuestion.processRequest(addQuestion.java:58) at servlets.addQuestion.doGet(addQuestion.java:82) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) at java.lang.Thread.run(Thread.java:619) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'option, answer) values (10, 10, 1, 'name', 'jayesh:pratik:priyanka:pruthika;', 1' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33) ... 34 more Mar 30, 2011 2:27:23 PM org.hibernate.util.JDBCExceptionReporter logExceptions WARNING: SQL Error: 1064, SQLState: 42000 Mar 30, 2011 2:27:23 PM org.hibernate.util.JDBCExceptionReporter logExceptions SEVERE: 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 'option, answer) values (10, 10, 1, 'name', 'jayesh:pratik:priyanka:pruthika;', 1' at line 1
-----------------------------------------------------------------------------------------
so please help me any body to solve this problem, please give me solution in as soon as possible.
thanks
|