我做了一个小示例程序,使用 java Hibernate 将数据插入 MySQL 数据库表。一切顺利,我得到了结果
“信息:模式更新完成 Hibernate:插入项目(itemcode,itemdiscription,itemprice,itemId)值(?,?,?,?) 构建成功(总时间:2 秒)”
我的映射文件和配置文件没问题。 但是当我在命令提示符下运行查询以获取更新的值时,它不会显示我的 java pojo 类输入的值。 这是为什么??? 请考虑我为此使用了 netbeans 7.1。
映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="firsthibernetapp.Item" table="items">
<id name="iid" type="int" column="itemId" >
<generator class="assigned"/>
</id>
<property name="icode">
<column name="itemcode"/>
</property>
<property name="idiscription">
<column name="itemdiscription"/>
</property>
<property name="iprice">
<column name="itemprice"/>
</property>
</class>
</hibernate-mapping>
hibernet.cfg.xml 文件:
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306 /combo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">********</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
代码:
package firsthibernetapp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstHibernetApp {
public static void main(String[] args) {
Session session = null;
try{
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Item item = new Item();
System.out.println("Inserting Record");
item.setIid(5);
item.setIcode("FX00010");
item.setIdiscription("Apple");
item.setIprice(10);
session.save(item);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.flush();
session.close();
}
}
}
`
最佳答案
add these lines..
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction(); //new line
Item item = new Item();
session.save(item);
System.out.println("Done");
tx.commit(); //new line
}catch(Exception e){
...
关于java - hibernate 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547581/