gpt4 book ai didi

java - 数据未使用 hibernate 插入,但没有给出错误?

转载 作者:搜寻专家 更新时间:2023-11-01 01:29:53 24 4
gpt4 key购买 nike

我正在尝试开始使用 Hibernate,但由于某种原因无法插入数据。它似乎工作正常,因为没有给出错误,但是当我检查数据库时,表是空的。我不认为它与数据库本身的连接失败了,因为当我将表名更改为映射 xml 中的非现有表名时,Hibernate 会即时创建它(但正如我所说,没有插入数据) .有谁知道可能是什么问题?

这是我的代码:

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/intex</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.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.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="intex.hbm.xml"/>
</session-factory>
</hibernate-configuration>

我的映射 xml:

<hibernate-mapping>
<class name="com.intex.uni.courses.Course" table="course">
<id name="id" column="id" >
<generator class="increment"/>
</id>

<property name="name" column="name" />
<property name="description" column="description" />
<property name="url" column="url" />
<property name="code" column="code" />
</class>
</hibernate-mapping>

还有我的测试客户端:

public class HibernateTest {

public static void main(String[] args) {

Session session = null;

try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Course course = new Course();
course.setDescription("Description");
course.setName("NAME");
course.setUrl("http://www.url.com");
session.save(course);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.flush();
session.close();
}
}
}

我真的希望有人能够帮助我!提前致谢:)

最佳答案

在主类中使用此代码并进行测试。

Session session = null;
Transaction txn = null;
try {
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
txn = session.beginTransaction();
Course course = new Course();
course.setDescription("Description");
course.setName("NAME");
course.setUrl("http://www.url.com");
session.save(course);
txn.commit();

} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (!txn.wasCommitted()) {
txn.rollback();
}

session.flush();
session.close();
}

关于java - 数据未使用 hibernate 插入,但没有给出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4431059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com