Uğurcan Şengit
Uğurcan Şengit

Reputation: 1026

Insertion fail with SQL Grammar Exception in Hibernate MySQL 5

I'm working on a project with hibernate technology. I got my POJO classes from hibernate reveng system, then I tried to test my project set-up with a saving database process. This is where I get my "could not insert: [tables.Users]" error. I'll share the necessary classes. This is saving Database class.

static boolean SaveDatabase(Users object) {


    Session session = null;
    try {

        session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.save(object);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            System.out.println(e.getMessage());
            return false;
        }
    } finally {
        session.close();
    }
    return true;
}

My configurations and table classes are correct. This is test class;

public class Test {
public static void main(String[] args) {
    // Test RegisterUser and GetUsersWithId in here

    LogIn test = new LogIn();
    Users user = new Users();

    user.setUserEmail("email");
    user.setUserAdress("adres here");
    user.setUserFbId(3);
    test.RegisterUsers(user);
}
}

And this is Stack Trace :

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
could not insert: [tables.Users]

When run my test program in debug mode session.save(object); line gives an exception and my program jumps into catch block. Also my transaction and session is not null. There are two pics of my debug mode that can help.

My passes class to the database. I'm not familiar with these hashsets, so there could be something wrong. Some of the varieble's values when debugging is in catch block. e = SQLGrammarException sent out here

Thanks for any help.

EDIT 3: Edited Stack trace

    Hibernate: insert into mobil.mobil.users (UserFbId, UserFbToken, UserName, UserLastName, UserEmail, UserAdress, UserFavouritedTopicsCount, UserCreatedTopicsCount, UserRecommendedTopicsCount, UserFollowingsCount, UserFollowersCount, UserBio, UserProfilePicUrl, UserIsOnline, UserPoint) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
org.hibernate.exception.SQLGrammarException: could not insert: [tables.Users]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2176)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2656)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:563)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:551)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:547)
    at DAO.LogIn.SaveDatabase(LogIn.java:55)
    at DAO.LogIn.RegisterUsers(LogIn.java:16)
    at Test.main(Test.java:14)
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 '.users (UserFbId, UserFbToken, UserName, UserLastName, UserEmail, UserAdress, Us' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
    ... 18 more

Hibernate Config. file :

<?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 name="">
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">diobookbla</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mobil</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.default_schema">mobil</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.search.autoregister_listeners">false</property>
        <mapping class="tables.Users" resource="Users.hbm.xml" />
        <mapping class="tables.Topicrecommend" resource="Topicrecommend.hbm.xml" />
        <mapping class="tables.Posts" resource="Posts.hbm.xml" />
        <mapping class="tables.Location" resource="Location.hbm.xml" />
        <mapping class="tables.Topics" resource="Topics.hbm.xml" />
        <mapping class="tables.Favouritetopics" resource="Favouritetopics.hbm.xml" />
        <mapping class="tables.Postlike" resource="Postlike.hbm.xml" />
        <mapping class="tables.Userfollow" resource="Userfollow.hbm.xml" />
        <mapping class="tables.Mention" resource="Mention.hbm.xml" />
    </session-factory>
</hibernate-configuration>

EDIT 2 : Users.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">
<!-- Generated Dec 11, 2012 4:55:13 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="tables.Users" table="users" catalog="mobil">
        <id name="userId" type="java.lang.Integer">
            <column name="UserId" />
            <generator class="identity" />
        </id>
        <property name="userFbId" type="java.lang.Integer">
            <column name="UserFbId" />
        </property>
        <property name="userFbToken" type="string">
            <column name="UserFbToken" />
        </property>
        <property name="userName" type="string">
            <column name="UserName" />
        </property>
        <property name="userLastName" type="string">
            <column name="UserLastName" />
        </property>
        <property name="userEmail" type="string">
            <column name="UserEmail" />
        </property>
        <property name="userAdress" type="string">
            <column name="UserAdress" />
        </property>
        <property name="userFavouritedTopicsCount" type="string">
            <column name="UserFavouritedTopicsCount" />
        </property>
        <property name="userCreatedTopicsCount" type="string">
            <column name="UserCreatedTopicsCount" />
        </property>
        <property name="userRecommendedTopicsCount" type="string">
            <column name="UserRecommendedTopicsCount" />
        </property>
        <property name="userFollowingsCount" type="java.lang.Integer">
            <column name="UserFollowingsCount" />
        </property>
        <property name="userFollowersCount" type="java.lang.Integer">
            <column name="UserFollowersCount" />
        </property>
        <property name="userBio" type="string">
            <column name="UserBio" />
        </property>
        <property name="userProfilePicUrl" type="string">
            <column name="UserProfilePicUrl" />
        </property>
        <property name="userIsOnline" type="java.lang.Boolean">
            <column name="UserIsOnline" />
        </property>
        <property name="userPoint" type="java.lang.Integer">
            <column name="UserPoint" />
        </property>
        <set name="topicses" table="topics" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="TopicUserId" />
            </key>
            <one-to-many class="tables.Topics" />
        </set>
        <set name="mentionsForMentionedId" table="mention" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="MentionedId" />
            </key>
            <one-to-many class="tables.Mention" />
        </set>
        <set name="favouritetopicses" table="favouritetopics" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="UserId" />
            </key>
            <one-to-many class="tables.Favouritetopics" />
        </set>
        <set name="mentionsForMentionerId" table="mention" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="MentionerId" />
            </key>
            <one-to-many class="tables.Mention" />
        </set>
        <set name="postlikes" table="postlike" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="UserId" />
            </key>
            <one-to-many class="tables.Postlike" />
        </set>
        <set name="userfollowsForFollowingId" table="userfollow" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="FollowingId" />
            </key>
            <one-to-many class="tables.Userfollow" />
        </set>
        <set name="topicrecommends" table="topicrecommend" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="UserId" />
            </key>
            <one-to-many class="tables.Topicrecommend" />
        </set>
        <set name="userfollowsForFollowerId" table="userfollow" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="FollowerId" />
            </key>
            <one-to-many class="tables.Userfollow" />
        </set>
    </class>
</hibernate-mapping>

Upvotes: 0

Views: 6733

Answers (1)

Johanna
Johanna

Reputation: 5293

OK, now I got it, where the problem is. mobil.mobil.users is nonsense, mobil.users would by correct and also users would work, because you have chosen the correct database in the connect string.

You've defined the database name at least three times:

  1. In your connect string: <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mobil</property>

  2. As the default schema: <property name="hibernate.default_schema">mobil</property>

  3. As catalog in the class mapping: <class name="tables.Users" table="users" catalog="mobil">

It is absolutely sufficient to define the database name in the connect string (1.). Both 2. and 3. you can remove; at least one of the two you must remove.


One remark to the question marks in the logging: Hibernate never shows the concrete values in the sql log. It always shows question marks. This is due to a JDBC limitation. Nevertheless the correct values are passed to the database. If you want to see the actual values, then you have to use a separate JDBC logging utility like log4jdbc.

Upvotes: 1

Related Questions