我有以下模型類:問題在休眠
package com.swaranga.model;
public final class Book
{
private Long id;
private String title;
private String isbn;
public Book(){}
public Book(String title, String isbn)
{
this.title = title;
this.isbn = isbn;
}
public final Long getId(){
return id;
}
private final void setId(Long id)
{
this.id = id;
}
public final String getTitle()
{
return title;
}
public final void setTitle(String title)
{
this.title = title;
}
public final String getIsbn()
{
return isbn;
}
public final void setIsbn(String isbn)
{
this.isbn = isbn;
}
//assume valid equals and hashcode
}
的具有以下映射文件Book.hbm.xml:
<hibernate-mapping>
<class name="com.swaranga.model.Book" table="book">
<id name="id" type="long">
<generator class="native"/>
</id>
<property name="title" column="title" type="string"/>
<property name="isbn" column="isbn" type="string"/>
</class>
</hibernate-mapping>
以下數據庫模式:
CREATE TABLE `hibernatetest`.`book` (
`id` int(10) unsigned NOT NULL auto_increment,
`title` varchar(45) NOT NULL,
`isbn` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
以下休眠配置文件:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateTest </property>
<property name="connection.username"> root </property>
<property name="connection.password"> latitude </property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="myeclipse.connection.profile">mysql</property>
<mapping resource="com\swaranga\model\Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
最後下面的代碼堅持一個Book
對象:
public class Main
{
public static void main(String[] args)
{
File f = new File("hibernate.cfg.xml");
Configuration cfg = new Configuration();
SessionFactory sessionFactory = cfg.configure(f).buildSessionFactory();
Session s = sessionFactory.openSession();
s.beginTransaction();
s.save(new Book("JDBC", "[email protected]#"));
s.flush();
s.disconnect();
}
}
我得到在控制檯下面的輸出:
Hibernate: insert into book (title, isbn) values (?, ?)
但是,當我檢查我的數據庫中,有沒有條目。
對於這樣一個長期的問題抱歉,但我覺得有必要提供所有的細節。請幫忙。提前致謝。
明白了。我不得不在s.save()之後說s.getTransaction()。commit();''現在它就像一個魅力!謝謝! – 2011-06-11 01:32:38
很高興工作! :) – 2011-06-11 01:33:07
我的第一個Hibernate程序。哇噢! – 2011-06-11 01:34:20