Hibernate不会插入数据库

时间:2013-04-24 20:06:27

标签: mysql hibernate insert

现在我有一个非常奇怪的问题,我无法理解。

我已经正确配置了休眠。我可以毫无问题地从我的mysql数据库加载数据。但是我无法插入数据。这是我的hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bookmaker</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="javax.persistence.validation.mode">none</property>

<mapping class="de.wettprofi.objects.Bookmaker"/>
<mapping class="de.wettprofi.objects.Match"/>
<mapping class="de.wettprofi.objects.LogEntry"/>

</session-factory>
</hibernate-configuration>

这是关于LogEntry类的。以下是一些应该将对象持久化到数据库中的代码:

public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    {
        BufferedReader reader = request.getReader();
        String json = reader.readLine();

        try {
            LogEntry log_entry = null;

            if (json != null && !json.isEmpty()) {
                log_entry = new LogEntry();

                JSONParser parser = new JSONParser();
                JSONObject json_dict = (JSONObject) parser.parse( json );

                //initalize proper LogEntry object
            } 
            if( log_entry != null ) {
                Session session = get_hibernate_session();
                System.out.println("Logging of LogEntry into the database\n" + log_entry.toString() );
                session.save( log_entry );
                session.flush();
                System.out.println("Logging DONE");
            }

        } catch( Exception e ) {
            e.printStackTrace();
        }
    }



    public Session get_hibernate_session()
    {
        //Opening a hibernate session
        SessionFactory sessionFactory = null;
        try {
            Configuration hibConfiguration = new Configuration().addResource("hibernate.cfg.xml").configure();       
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(hibConfiguration.getProperties()).buildServiceRegistry();
            sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
        } catch( Exception e ) {
            e.printStackTrace();
        }

        return sessionFactory.withOptions().openSession();
    }

这就是LogEntry类对象的样子(省略了getters和setter):

@Entity
@Table( name = "LogEntries" )
public class LogEntry {

    public static int MESSAGE = 1;
    public static int BOOKMAKER = 2;
    public static int CLICKLOG = 3;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column( name = "lid" )
    public int lid;

    @Column( name = "id" )
    public String id;

    @Column( name = "date" )
    public Date date;

    @Column( name = "type" )
    public int type;

    @Column( name = "message" )
    public String message;

    @Column( name = "bookmaker" )
    public String bookmaker;

    @Column( name = "match_id" )
    public int match_id;

    @Column( name = "result" )
    public String result;


    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("      lid = " + lid  + "\n");
        sb.append("       id = " + id  + "\n");
        sb.append("     date = " + date.toString()  + "\n");
        sb.append("     type = " + type  + "\n");
        sb.append("  message = " + message  + "\n");
        sb.append("bookmaker = " + bookmaker  + "\n");
        sb.append(" match_id = " + match_id  + "\n");
        sb.append("   result = " + result  + "\n");
        return sb.toString();
    }

所以,当我现在运行我的tomcat实例并查看发生了什么时,我得到以下输出:

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Apr 24, 2013 9:55:18 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Apr 24, 2013 9:55:18 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Logging of LogEntry into the database
      lid = 0
       id = 50569803719166097161
     date = Mon Apr 22 21:01:53 CEST 2013
     type = 1
  message = MainVC
bookmaker = null
 match_id = 0
   result = null

Hibernate: insert into LogEntries (bookmaker, date, id, match_id, message, result, type) values (?, ?, ?, ?, ?, ?, ?)
Logging DONE

然而,在查看我的数据库后,发现没有任何内容写入表中。

这是我的表架构:

mysql> describe LogEntries;
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| lid       | int(11)      | NO   | PRI | NULL    | auto_increment |
| bookmaker | varchar(255) | YES  |     | NULL    |                |
| date      | datetime     | YES  |     | NULL    |                |
| id        | varchar(255) | YES  |     | NULL    |                |
| match_id  | int(11)      | YES  |     | NULL    |                |
| message   | varchar(255) | YES  |     | NULL    |                |
| result    | varchar(255) | YES  |     | NULL    |                |
| type      | int(11)      | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

有没有人知道可能导致这个问题的原因。我很无能:(

2 个答案:

答案 0 :(得分:0)

根据Hibernate文档,每个属性需要declare get/set pairs。这些方法可以是公开的,受保护的或私有的,但它们必须存在。

答案 1 :(得分:0)

实体类应具有该属性的getter和setter。

在获得会话后,您还需要开始交易。

http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html

Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     sess.save(entityObjectToBeinserted);
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }