Hibernate hello world example in eclipse

This is 2 of 8 parts of tutorial series

Tutorial Content:

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.

  1. Download hibernate framework.(I am using here latest hibernate version 4.1.9)
  2. Download any database.(I am using here sql server 2005)
  3. Download JDBC driver for database(I have downloaded jdbc driver for sql server 2005)
  4. Eclipse ide
  5. 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”

Click on finish and now our project is created
Create new folder “jars” under src folder so for that right click on project->new->folder

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 make User_table table in database using hibernate.

We will create User.java for creating above table in database.

1.User.java(Entity)

An entity can be considered as a lightweight persistence domain object. An entity defines a table in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole.
Create a new package org.arpit.javapostsforlearning to hold the java files. Right click on the “src” folder and then select New –> Package. Then provide the package name as org.arpit.javapostsforlearning and click on the “Finish” button.
Create a new Java file User.java under the package org.arpit.javapostsforlearning and add the following code:
@Entity is used for making a persistent pojo class.For this java class,you want to create a table in database.
@Entity(name=”User_table”) specify that create a table named “User_table” in database

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.

: 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:

Create a class named “HibernateMain.java” in src->org.arpit.javapostsforlearning
 
As we have discussed in our previous post,we have to create SessionFactory instance in order to communicate with Database in Hibernate

Project structure:

 4.Run it:

When you will run this application.You will get following output.
After execution of above program,you can check User_table table in your database.

5.SQL output:

Source code:

click to begin
6.1 MB .zip

Was this post helpful?

Comments

  1. 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:


    com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://localhost:1433;database=UserInfo sa

    1

    org.hibernate.dialect.SQLServer2005Dialect

    true

    create

  2. Ok, I get it fixed.
    I need tweek the dtd path a little in the hibernate.cfg.xml file.

    Thanks for a good tutorial.

    1. Hi Charlie,

      Even i am getting the same error. How did you fix it?
      What changes have you made?

      Thanks in advance.

      Swathi.

        1. 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.

  3. ” 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?

    1. this problem was due to the version of hibernate … now it is solved .. i needed to download hibernate version 4.1

      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);

    1. 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

  4. 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!

  5. 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

  6. SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
    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.(Configuration.java:197)
    at dbtest.userTest.main(userTest.java:15)

    what was the provlem

  7. 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

  8. мар 15, 2014 5:10:10 PM org.hibernate.annotations.common.Version
    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 entry
    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

  9. In the main class 15th line xxx.bulidServiceRegistry(); is not allowing showing error plz give me suggestions early

    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); Read more at http://javapostsforlearning.blogspot.com/2013/01/

    1. 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!

  10. 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

  11. 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

  12. don't put the port number 1433 here
    [jdbc:sqlserver://MINHPHUONG-PC//SQLEXPRESS;database=User_table]
    in the hibernate.cfg.xml

  13. 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,



    com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/test root mysql

    1

    org.hibernate.dialect.MySQLDialect

    true create

    thakn you kor your time .

    1. 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

  14. 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 .

    1. 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

  15. 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.

  16. 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.

    com.mysql.jdbc.Driver jdbc:mysql://localhost/UserInfo root ***

    Hope this helps anyone using MySQL.
    Thanks a lot for this tutorial.

  17. 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)

  18. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *