gpt4 book ai didi

java - 使用 Hibernate SessionFactory 插入不起作用的值

转载 作者:行者123 更新时间:2023-11-30 03:19:49 24 4
gpt4 key购买 nike

我正在 Spring MVC 中使用 Hibernate 作为 ORM..

在我的模块中,我调用表单操作将值存储到表中。但数据未插入该表中。但我在日志中没有任何错误。

我尝试使用 sessionFactory 的代码是,

        String querys = "insert into reconcile_process (process_type,fk_last_modified_by,fk_bank_stmt_id)"
+ " values (?,?,?)";
Connection connections = sessionFactory.getCurrentSession().connection();
PreparedStatement stmt = connections.prepareStatement(querys);
stmt.setString(1, "Auto");
stmt.setInt(2, 1);
stmt.setInt(3, 251);
stmt.executeUpdate();;
connections.close();

但以同样的方式,我可以使用 JDBC 驱动程序插入值,如下所示,

        private static final String DB_DRIVER = "org.postgresql.Driver";
private static final String DB_CONNECTION = "jdbc:postgresql://localhost:5432/xxxxx";
private static final String DB_USER = "xxxxxx";
private static final String DB_PASSWORD = "xxxxx";

Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String querys = "INSERT INTO reconcile_process "
+ "(process_type,fk_last_modified_by,fk_bank_stmt_id) VALUES"
+ "(?,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(querys);
preparedStatement.setString(1, "Type");
preparedStatement.setLong(2, 45);
preparedStatement.setLong(3, 251);
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}

private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}

谁能指出问题出在哪里吗?

最佳答案

请检查默认包中的 hibernate.cfg.xml 文件

     <property name="hibernate.connection.autocommit">true</property> 

设置存在。我认为您的操作是正确的,但由于 Commit 操作,您没有得到正确的结果。

或者因为您想要保存传递​​给 session 工厂域对象

session.save(obj); 
txn.commit();

关于java - 使用 Hibernate SessionFactory 插入不起作用的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31604908/

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