Table of Contents
This is 2 of 8 parts of tutorial series
Tutorial Content:
- Introduction to hibernate framework
- Hibernate hello world example in eclipse
- Difference between openSession and getCurrentSession
- Hibernate one to one mapping example
- Hibernate one to many mapping example
- Hibernate many to many mapping example
- Hibernate inheritance:Table per class hierarchy
- Hibernate inheritance:table per subclass
- Hibernate inheritance:Table per concrete class
- Difference between openSession and getCurrentSession
- Difference between get and load
- Spring MVC Hibernate MySQL CRUD example
- Spring Rest hibernate example
After basic understanding of hibernate framework.We are ready to start working on hibernate In this post,we will configure hibernate in eclipse and write our first hibernate program.For configuring hibernate,there are some prerequisites which you need to have on your system.
- Download hibernate framework.(I am using here latest hibernate version 4.1.9)
- Download any database.(I am using here sql server 2005)
- Download JDBC driver for database(I have downloaded jdbc driver for sql server 2005)
- Eclipse ide
- JDK 1.5 or above
Now,In eclipse IDE,click on File->new
Click on other and then select java project
Click on next and Write project name.I have writtern here “Hibernate4HelloWorldProject”
Write folder name as “jars”
click on finish and empy jar folder will be created in src folder.
Now we will add the hibernate 4 libraries to the project. Extract the “hibernate-release-4.1.9.Final” file if you have not extracted. Now go to the “hibernate-release-4.1.9.Final->lib->required” directory and then copy all the jar files (Ctrl+C) and paste on the jars directory (of our project) in the Eclipse IDE.
Also download jdbc driver for your database and copy that jar to jars
Note- location of above jar files may vary from versions to versions. So if you are using other versions than 4.1.9 then you need to find jars in that version.
Now add all the jars to “Java Build Path”. Right click on the “Hibernate4HelloWorldProject” in project explorer and then select properties. Then select “Java Build Path” –> Libraries and then click on the “Add JARs” button. And add all the libraries to Java Build Path.
Click on OK.
you are done with configuring hibernate in eclipse.
Now we will write our first hibernate application.For configuring hibernate in eclipse,please refer previous post.I am using SQL server 2005 as database.
We will create User.java for creating above table in database.
1.User.java(Entity)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package org.arpit.javapostsforlearning; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity(name="User_table") public class User { @Id int userId; @Column(name="User_Name") String userName; String userMessage; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserMessage() { return userMessage; } public void setUserMessage(String userMessage) { this.userMessage = userMessage; } } |
2.Hibernate configuration XML:
After configuring hibernate in eclipse,we need to configure “hibernate.cfg.xml” for database configuration and other related parameters.By default,hibernate searches for a configuration file in a project’s root directory.Create a file named “hibernate.cfg.xml” in src folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<hibernate-configuration> Â Â Â <session-factory> Â Â Â Â Â Â Â <!-- Database connection settings --> Â Â Â Â Â Â Â <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> Â Â Â Â Â Â Â <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property> Â Â Â Â Â Â Â <property name="connection.username">sa</property> Â Â Â Â Â Â Â <property name="connection.password"></property> Â Â Â Â Â Â Â <!-- JDBC connection pool (use the built-in) --> Â Â Â Â Â Â Â <property name="connection.pool_size">1</property> Â Â Â Â Â Â Â <!-- SQL dialect --> Â Â Â Â Â Â Â <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property> Â Â Â Â Â Â Â <!-- Echo all executed SQL to stdout --> Â Â Â Â Â Â Â <property name="show_sql">true</property> Â Â Â Â Â Â Â <!-- Drop and re-create the database schema on startup --> Â Â Â Â Â Â Â <property name="hbm2ddl.auto">create</property> Â Â Â Â Â Â <mapping class="org.arpit.javapostsforlearning.User"></mapping> Â Â Â </session-factory> </hibernate-configuration> |
: Need to specify JDBC driver class.
 :specify JDBC URL to the database instance.
 ” >:Specify database username
” >:Specify database password
” >:This property makes Hibernate generate the appropriate SQL for the chosen database.
hibernate.connection.pool_size ” >:This property limits the number of connections waiting in the Hibernate database connection pool.
” >:If you specify this property to be true then all sql statement will be printed to console.
” >:It specify operation on your database schema.Whether to drop and recreate your database schema or update current schema.
 >:Here you need to specify all java classes for which you want to create a table in database.You need to specify all entity classes here.
3.Main class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package org.arpit.javapostsforlearning; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateMain { public static void main(String[] args) { Configuration configuration=new Configuration(); configuration.configure(); ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sf=configuration.buildSessionFactory(sr); User user1=new User(); user1.setUserName("Arpit"); user1.setUserMessage("Hello world from arpit"); User user2=new User(); user2.setUserName("Ankita"); user2.setUserMessage("Hello world from ankita"); Session ss=sf.openSession(); ss.beginTransaction(); //saving objects to session ss.save(user1); ss.save(user2); ss.getTransaction().commit(); ss.close(); } } |
Project structure:
 4.Run it:
1 2 3 4 5 6 7 8 |
Hibernate: drop table User_table Hibernate: create table User_table (userId int identity not null, userMessage varchar(255), User_Name varchar(255), primary key (userId)) Jan 29, 2013 9:38:32 PM org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000230: Schema export complete Hibernate: insert into User_table (userMessage, User_Name) values (?, ?) Hibernate: insert into User_table (userMessage, User_Name) values (?, ?) |
Te code does not work due to configuration xml file.
The errors are:
May 29, 2013 5:02:55 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 29, 2013 5:02:56 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.9.Final}
May 29, 2013 5:02:56 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 29, 2013 5:02:56 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 29, 2013 5:02:56 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 29, 2013 5:02:56 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2023)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1935)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1914)
at org.arpit.javapostsforlearning.HibernateMain.main(HibernateMain.java:14)
Caused by: org.dom4j.DocumentException: Error on line 2 of document : The document type declaration for root element type “hibernate-configuration” must end with '>'. Nested exception: The document type declaration for root element type “hibernate-configuration” must end with '>'.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2015)
… 3 more
//////////////////////////////////
The config xml file I use is following:
Ok, I get it fixed.
I need tweek the dtd path a little in the hibernate.cfg.xml file.
Thanks for a good tutorial.
Hi Charlie,
Even i am getting the same error. How did you fix it?
What changes have you made?
Thanks in advance.
Swathi.
Did you get it fixed Swathi?
Check your DTD in the second line.
there may be space in this – “http://hibernate.org/dtd/ hibernate-configuration-3.0.dtd”.Remove the white space if any.
Always once you have completed the xml file try opening it in IE. You might catch some errors like this.
” SessionFactory sf=configuration.buildSessionFactory(sr); ” in HibernateMain.java gives an error … saying buildSessionFactory() does not accept any arguments .
what's the problem am i missing any jar file or what?
this problem was due to the version of hibernate … now it is solved .. i needed to download hibernate version 4.1
Hi —
For for Hibernate 4.3.5 I use:
import org.hibernate.service.ServiceRegistry;
//import org.hibernate.service.ServiceRegistryBuilder; <-- remove this ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build(); SessionFactory sf = configuration.buildSessionFactory(serviceRegistry);
good job. thaks
Nice example.. Thx.
One correction. user.setUserId() needs to be added to execute the commit.
I confirm user.setUserId() must be added to execute the commit
Really the tutorial is so good for understanding the advance concept like struts,springs,hibernate …..
Good job sir….who will follow java-internal
set a userId for each user
user1.setUserId(1);
user2.setUserId(2);
There should be an additional annotation @GeneratedValue in User.java file for userId variable:
@Id
@GeneratedValue
int userId;
and hardcoding userId won't be needed
hey, thanks arpith and ankitha…. good job keep it up man
Make sure you have the configuration correctly. I got the same errors but got it bypassed.
……………..
THEN the rest of the configuration file. Good luck!
hi
Help me out pls,
i did the same example as above and using mysql server and i did change the properties in configuration file.
Oct 23, 2013 11:55:02 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Oct 23, 2013 11:55:02 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Oct 23, 2013 11:55:02 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
Oct 23, 2013 11:55:02 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 23, 2013 11:55:02 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Oct 23, 2013 11:55:02 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread “main” org.hibernate.MappingException: invalid configuration
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2091)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2008)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1987)
at org.arpit.javapostsforlearning.HibernateMain.main(HibernateMain.java:14)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 25; Document is invalid: no grammar found.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2088)
… 3 more
SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.(Configuration.java:197)
SLF4J: Your binding is version 1.5.5 or earlier.
SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x
Exception in thread “main” java.lang.NoSuchMethodError: org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/StaticLoggerBinder;
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:121)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:268)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:241)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:254)
at org.hibernate.cfg.Configuration.
at dbtest.userTest.main(userTest.java:15)
what was the provlem
What a great tutorial Sir ….Now I have no confusion about hibernate word…..
Its very easy to understand, But i am biggner to the hibernate and i am facing the following exception while using your tutorial.
Jan 03, 2014 11:48:31 AM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Jan 03, 2014 11:48:31 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.9.Final}
Jan 03, 2014 11:48:31 AM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
Jan 03, 2014 11:48:31 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 03, 2014 11:48:31 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jan 03, 2014 11:48:31 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread “main” org.hibernate.MappingException: invalid configuration
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2018)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1935)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1914)
at org.arpit.javapostsforlearning.Main.main(Main.java:14)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 25; Document is invalid: no grammar found.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:226)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:881)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2015)
… 3 more
мар 15, 2014 5:10:10 PM org.hibernate.annotations.common.Version entry
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
мар 15, 2014 5:10:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.9.Final}
мар 15, 2014 5:10:10 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
мар 15, 2014 5:10:10 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
мар 15, 2014 5:10:10 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
мар 15, 2014 5:10:10 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
мар 15, 2014 5:10:10 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Exception in thread “main” org.hibernate.MappingException: Unable to load class [ org.arpit.javapostsforlearning.User] declared in Hibernate configuration
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2139)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2087)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2067)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2020)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1935)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1914)
at by.bsu.ramaniuk.HibernateMain.main(HibernateMain.java:14)
Caused by: java.lang.ClassNotFoundException: org.arpit.javapostsforlearning.User
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:192)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2136)
… 6 more
when hibernate.cfg.xml file is load in struts2 web application
In the main class 15th line xxx.bulidServiceRegistry(); is not allowing showing error plz give me suggestions early
Hi —
For for Hibernate 4.3.5 I use:
import org.hibernate.service.ServiceRegistry;
//import org.hibernate.service.ServiceRegistryBuilder; <-- remove this ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build(); SessionFactory sf = configuration.buildSessionFactory(serviceRegistry); Read more at http://javapostsforlearning.blogspot.com/2013/01/…
See my comment above (search this page for mbird)
Ooops I meant this as a reply to a post above. I added the correct reply to the actual post so please delete or disregard this post 🙂 Thanks!
anybody help me this exception:
org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at hibernate.test.test.main(test.java:37)
Caused by: org.postgresql.util.PSQLException: ERROR: relation “tbl_account” does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2161)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1890)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:559)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:363)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
… 13 more
Error! Details:
org.hibernate.exception.SQLGrammarExceptioncould not execute statement
i downloaded the microsoft mysql server.i installed that .but i don't know how to run mysql from command promt
please let me know
Install WAMP SERVER (MYSQL+Apache).
Then you have PHP console, you can easily manage MySQL statements.
don't put the port number 1433 here
[jdbc:sqlserver://MINHPHUONG-PC//SQLEXPRESS;database=User_table]
in the hibernate.cfg.xml
Hi,
i m using mysql and spring eclipse.
i m new to hibernate.
i got these error.
i need help to solve Error.
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: drop table if exists User_table
Hibernate: create table User_table (userId integer not null, userMessage varchar(255), User_Name varchar(255), primary key (userId))
Exception in thread “main” org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [org.arpit.javapostsforlearning.User#0]
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:137)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at org.arpit.javapostsforlearning.HibernateMain.main(HibernateMain.java:55)
HibernateMain.java
package org.arpit.javapostsforlearning;
import org.apache.log4j.PropertyConfigurator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateMain {
public static void main(String[] args) {
Configuration conf=new Configuration();
conf.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( conf.getProperties() ).build();
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
User user1=new User();
user1.setUserName(“vinod”);
user1.setUserMessage(“Hello world from vinod”);
User user2=new User();
user2.setUserName(“raaj”);
user2.setUserMessage(“Hello world from vinodaraaj”);
Session ss=sf.openSession();
ss.beginTransaction();
//saving objects to session
ss.save(user1);
ss.save(user2);
ss.getTransaction().commit();
ss.close();
}
}
Entity: User.java
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity(name=”User_table”)
public class User {
@Id
int userId;
@Column(name=”User_Name”)
String userName;
String userMessage;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
Hibernateconfig xml,
thakn you kor your time .
You error is because adding object with same Primary key to the database, you can simple resolve the issue by:
1. Adding user ID to objects, e.g.
user1.setUserId(2)
2. Set auto increment to the primary key in database and input the following annotation to Class User:
@GeneratedValue(strategy=GenerationType.AUTO)
Hope it helps
Hi,
i m using mysql and spring eclipse.
i m new to hibernate.
i have only this warning now ..
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
thakn you for your time .
Hi man,
check the log4j.xml file for an appender for the org.jboss.logging class.
check that appender exist as well as it associated Category definition (in the bottom part of the file).
Good luck
If I don't add the @GeneratedValue annotation before the usedId attribute I get a Non-Unique object hibernate exception.
Other than that it works.
This worked for me as well.
Thank you for the suggestion.
1) To solve the problem of not identifying the “hibernate.cfg.xml” file in the project I moved the file into src directory. Then it worked fine.
2) When using MySQL server with this code I fixed a error with connection by using the following properties.
Hope this helps anyone using MySQL.
Thanks a lot for this tutorial.
While running your example i have an error like..
Exception in thread “main” org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.arasu.hibernate.row.insertion.BookStore#0]
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:137)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.arasu.hibernate.row.insertion.HibernateBookStoreMain.main(HibernateBookStoreMain.java:30)
Jun 9, 2015 10:57:37 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Jun 9, 2015 10:57:37 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.10.Final}
Jun 9, 2015 10:57:37 AM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
Jun 9, 2015 10:57:37 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 9, 2015 10:57:37 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jun 9, 2015 10:57:37 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2165)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2056)
at com.sadiq.HibernateMain.main(HibernateMain.java:14)
Caused by: org.dom4j.DocumentException: Error on line 2 of document : The processing instruction target matching “[xX][mM][lL]” is not allowed. Nested exception: The processing instruction target matching “[xX][mM][lL]” is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2157)
… 3 more
I am getting this error.. How can i solve it?
Nice article on the Hibernate setup.
For setting hibernate and sample example code you can refer to following link.
http://techpost360.blogspot.in/2015/07/configurin…