1

I've been trying to set up a little hibernate/spring MVC project.

I've gotten the Spring .jsp page to display data from the database, but i cannot figure out how to have hibernate save the objects to the database.

Here is my (relevant) Code:

GroupDAOImpl.java (the method)

@Override
public void saveGroup(Group group){
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    session.save(group);

    transaction.commit();
    session.close();
}

HelloController.java Method:

 public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Group group) throws Exception {
    groupDAO.saveGroup(group);
    return new ModelAndView("redirect:list.htm");
}

jsp Page:

<form:form action="add.htm" commandName="group">
<table>
    <tr>
        <td>group Name :</td>
        <td><form:input path="name"/></td>
    </tr>

    <tr>
        <td colspan="2"><input type="submit" value="Register"></td>
    </tr>
</table>

Log from the Server:

Hibernate: insert into groups (id, name, shoppingList_id) values (default, ?, ?)

Debugger Value of "group" in GroupDAOImpl saving method:

id = 2
name = "jjjj"

Any ideas? Greatly appreciated!

4

2 回答 2

0

据我所知,休眠属性需要以休眠为前缀,例如

<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />

解决这个问题,这可能是你的问题

于 2014-01-26T20:42:02.777 回答
0

实际上我们在日志中看到了 SQL 请求:

Hibernate: insert into groups (id, name, shoppingList_id) values (default, ?, ?)

我猜你解释得不好,你希望它是你现有对象的 SQL 更新查询。

如果要更新对象,SpringMVC 绑定提供的 Group 实例应该知道对象 id。实际上,表单不会发送 Group id,因此您的应用程序无法知道应该更新哪个对象。

即使知道 ID,也需要调用 Session.merge 而不是 Session.save :)

于 2013-04-25T22:14:05.107 回答