Configure MySql Database With Hibernate Mappings

Configure MySql Database

Configuring MySql database with hibernate is the same as with other databasses. The only difference will be connection url and the database dialect to be specified in the configuration file. This tips provides a basic example configuration file for configuaring the MySql with hibernate. But it doesn’t explain you installing the MySql database. If you are looing for installing MySql database please read it here : http://dev.mysql.com/downloads/

also read:

Sample URL is jdbc:mysql://localhost:3306/SampleDB. In this URL port 3306 is default for the mysql database. If you are not specifying that in the URL, it will assume the port is 3306.localhost can be replaced with your system IP address and machine name.SampleDB is the database or catelog name you have created. Every session factory can have only one database. if you want to use multiple database, create multiple session factory with different database names.

org.hibernate.dialect.MySQLDialect (Read: List of Hibernate Dialects) is the dialect name for MySQL database. Each database has its own dialect declared in the hibernate package.

<?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'>

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name='connection.driver_class'>com.mysql.jdbc.Driver</property>
        <property name='connection.url'>jdbc:mysql://localhost:3306/SampleDB</property>
        <property name='connection.username'>root</property>
        <property name='connection.password'>root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name='connection.pool_size'>1</property>

        <!-- SQL dialect -->
        <property name='dialect'>org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name='show_sql'>true</property>

        <!-- Mapping files -->
        <mapping resource='Author.hbm.xml'/>
    </session-factory>
</hibernate-configuration>

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. hemanth says:

    hi,
    I am unable to connect mysqldb using hibernate.i have to connect from onelinux system to anotherlinux system . and i gave the ip address of another linux system but am unable to connect db please help me on this issue.

    • suthukrish says:

      Hello Hemanth,

      Are you doing the developemnt in Linux system. Did you check whetheter all the network connection is proper. Can you post your connection code here?

      Thanks,
      Krishna

  2. hi,

    I am using hibernate and i have doubt in sessions. can u please guide to me.
    When am post (save or update) time only am using session.i.e begintranasaction and rollback and close functionalists. When i want to fetch some records from database am not following the begin transaction and close transaction .Can u please guide me is am followed is correct or not.

  3. hi, krishna

    could you send me info if in projects which use mysql 5.2.x and hibernate 4.2 there is a need to include mysql-connector-java-5.x.x-bin.jar to the hibernate user library in project

    thanks

  4. pawan tiwari says:

    hi,
    I am trying to login to my database from my web project.. but there is a probloem.here is the problem code..
    org.hibernate.exception.SQLGrammarException: could not execute query
    org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    org.hibernate.loader.Loader.doList(Loader.java:2223)
    org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
    org.hibernate.loader.Loader.list(Loader.java:2099)
    org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
    org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
    org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
    org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
    org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
    org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:811)
    com.sbj.service.CustomerDao.login(CustomerDao.java:25)
    com.sbj.controller.LoginController.execute(LoginController.java:61)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    And here is the code of controller and hibernate class..
    import java.util.List;

    import org.hibernate.Hibernate;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.Transaction;

    import com.sbj.persistance.HibernateSessionFactory;

    public class CustomerDao {

    public static boolean login(int userid,String password)
    {
    Session session=HibernateSessionFactory.getSession();
    Transaction tx=session.beginTransaction();
    Query query10=session.createQuery(“select count(*) from Login l where l.userid=:name and l.password=:pwd”);
    query10.setInteger(“name”, userid);

    query10.setString(“pwd”, password);

    //List list10=query10.list();
    Long count = (Long)query10.uniqueResult();
    tx.commit();
    session.close();
    if(count==1)
    {
    return true;

    }
    else
    {
    return false;
    }

    }

    }
    Controller clas..
    package com.sbj.controller;

    import java.util.Map;

    import org.apache.struts2.dispatcher.SessionMap;
    import org.apache.struts2.interceptor.SessionAware;

    import com.opensymphony.xwork2.ActionSupport;
    import com.sbj.service.CustomerDao;

    public class LoginController extends ActionSupport implements SessionAware
    {
    private Integer userid;
    private String password;

    private SessionMap sessionmap;

    public Integer getUserid() {
    return userid;
    }

    public void setUserid(Integer userid) {
    this.userid = userid;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    @Override
    public void setSession(Map map) {
    // TODO Auto-generated method stub
    sessionmap = (SessionMap) map;
    sessionmap.put(“login”,true);
    sessionmap.put(“userName”, userid);

    }

    public String execute()
    {
    System.out.println(“Your user id is.. “+userid);
    System.out.println(“Your password is.. “+password);
    if(CustomerDao.login(userid, password))
    {
    return SUCCESS;
    }
    else
    {
    return ERROR;
    }
    }

    }

  5. madhavi says:

    Hi,

    I am using hibernate (with c3P0)with MySQL DB.

    When my code is trying to connect to DB, I am getting the following exception:

    org.hibernate.exception.GenericJDBCException: Cannot open connection
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
    at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:140)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1551)
    at org.hibernate.loader.Loader.doQuery(Loader.java:673)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
    at org.hibernate.loader.Loader.doList(Loader.java:2217)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2108)
    at org.hibernate.loader.Loader.list(Loader.java:2103)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:94)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1570)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
    at com.rezolt.gateway.trigger.TriggerDeviceSensorAlarm.execute(TriggerDeviceSensorAlarm.java:50)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:525)
    Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128)
    at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:56)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
    … 14 more
    Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319)
    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525)
    … 17 more

    Any idea about this exception, please share.

    TIA,
    madhavi

Speak Your Mind

*