我在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;
}
有人能指出问题所在吗?
答案 0 :(得分:1)
如果您正在使用Hibernate,为什么不采取其优势
,尝试这样的事情 SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
txn = session.beginTransaction();
UrTableClass obj = new UrTableClass ();
obj.setDescription("Description");
obj.setName("NAME");
obj.setAge(28);
session.save(obj);
txn.commit();
答案 1 :(得分:1)
请检查默认包
中的hibernate.cfg.xml文件 <property name="hibernate.connection.autocommit">true</property>
设置存在。我认为你的操作是正确的但是因为提交操作你没有得到正确的结果。
或因您要保存的object of domain
课程传递给session factory
session.save(obj);
txn.commit();
答案 2 :(得分:0)
为了找到问题的根本原因 - 我建议以debug
模式启动服务器。然后使用F6
逐行调试。这有助于您跟踪objects
中传递的值。
如果你一直在使用hibernate,我强烈认为你错过了hibernate.cfg.xml
通过hibernate
保存在数据库中所需的一些重要配置。