0

我正在研究一个使用休眠技术的项目。我从 hibernate reveng 系统获得了我的 POJO 类,然后我尝试使用保存数据库过程来测试我的项目设置。这是我得到“无法插入:[tables.Users]”错误的地方。我将分享必要的课程。这是保存数据库类。

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

我的配置和表类是正确的。这是测试类;

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

这是堆栈跟踪:

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]

在调试模式下运行我的测试程序时 session.save(object); 行给出异常,我的程序跳转到 catch 块。我的交易和会话也不为空。我的调试模式有两张图片可以提供帮助。

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

谢谢你的帮助。

编辑 3:编辑堆栈跟踪

    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

休眠配置。文件 :

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

编辑 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>
4

1 回答 1

1

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.

于 2013-01-11T08:31:32.543 回答