java - 保存成功后无法更新

标签 java spring hibernate spring-mvc

我对 Spring MVC 还比较陌生。在我的 uploadPub.java 文件中 dService.saveDocument(doc);方法运行成功。我调用它是为了获取一个 Id 进行记录。然后我想用新值更新相同的记录。但还是没能做到。没有错误消息或异常。我使用的是 Spring 4.0.5 和 hibernate 4.3.5。这是文件。感谢您的帮助。

uploadPub.java

    public int uploadPub(MultipartFile filea) { 
    String originalName = null;
    String path = null;
    Documents doc = new Documents("", "", 'N', DateUtils.getNow());

    int docId = dService.saveDocument(doc);

    try {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        if (filea != null && filea.getSize() > 0) {
            File targetFile = new File("C:\\yayinDoc");
            if (!targetFile.exists()) {
                targetFile.mkdir();
            }
            originalName = filea.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalName);
            if (extension.equals("doc") || extension.equals("docx")) {
                path = targetFile.getPath() + "\\" + docId + "." + extension;
                inputStream = filea.getInputStream();
                outputStream = new FileOutputStream(path);

                int readBytes = 0;
                byte[] buffer = new byte[8192];
                while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                    outputStream.write(buffer, 0, readBytes);
                }
                outputStream.close();
                inputStream.close();

                Documents docUpdate = new Documents(docId, originalName, path, 'Y', DateUtils.getNow());

                dService.updateDocument(docUpdate);

                return docId;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

DocumentsService.java

@Transactional
@Service("documentsService")
public class DocumentsService extends GenericManagerImp<Documents> {

@Autowired
private DocumentsDao documentsDao;

public DocumentsService() {
    super();
}

public DocumentsService(DocumentsDao documentsDao) {
    this.documentsDao = documentsDao;
}


public int saveDocument(Documents doc) {
    documentsDao.saveDocument(doc);
    return doc.getDocId();
}


public void updateDocument(Documents doc) {
    documentsDao.updateDocument(doc);
}


public void deleteDocument(Documents doc) {
    documentsDao.deleteDocument(doc);
}

}

DocumentsDao.java

@Repository("documentsDAO")
public class DocumentsDao extends GenericDaoImp<Documents> {

public DocumentsDao() {
    super(Documents.class);
    this.sessionFactory = HibernateUtil.getSessionFactory();

}


public void saveDocument(Documents documents) {
    save(documents);
}


public void updateDocument(Documents doc) {
    update(doc);
}


public void deleteDocument(Documents doc) {
    delete(doc);
}
}

GenericDaoImp.java

public class GenericDaoImp<T> implements GenericDao<T> {

private Class<T> persistentClass;

protected SessionFactory sessionFactory;



public GenericDaoImp(final Class<T> persistentClass) {
    this.persistentClass = persistentClass;
    this.sessionFactory = HibernateUtil.getSessionFactory();
}

public GenericDaoImp(final Class<T> persistentClass, SessionFactory sessionFactory) {
    this.persistentClass = persistentClass;
    this.sessionFactory = sessionFactory;
}

public SessionFactory getSessionFactory() {
    return this.sessionFactory;
}

public Session getSession() {
    Session currentSession = getSessionFactory().openSession();

    return currentSession;
}

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}


public T save(T object) {
    getSession().save(object);
    return object;
}

public T persist(T object) {
    getSession().persist(object);
    return object;
}

public T update(T object) {
    getSession().update(object);
    return object;
}


public void delete(T object) {
    getSession().delete(object);
}
}

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


<!-- Enables the Spring MVC @Controller programming model -->
<tx:annotation-driven transaction-manager="hibernateTransactionManager"  proxy-target-class="true"/>
<mvc:annotation-driven />

<context:annotation-config />
<context:component-scan base-package="com.pub.controller" />
<context:component-scan base-package="com.pub.service" />
<context:component-scan base-package="com.pub.dao" />
<context:component-scan base-package="com.pub.model" />


<bean id="hibernateTransactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
   <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://xxx"></property>
    <property name="username" value="xxx"></property>
    <property name="password" value="xxx"></property>
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="hibernateProperties">
    <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>

</bean>

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="order" value="2" />
    <property name="prefix">
        <value>/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="order" value="1" />
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>

<mvc:default-servlet-handler />

最佳答案

了解hibernate object states.

问题是您正在使用update,但您的对象已分离。您可以通过两种方式解决;

  • 使用merge方法更新新创建的文档

    了解您的用例以及合并( This article ) 的使用

  • 使用同一个 session ,您总是在创建一个新 session 。所以相反,

    session currentSession = getSessionFactory().openSession();

    使用这样的东西,

    session currentSession = getSessionFactory().getCurrentSession();

更新

尝试更新您的 GenericDaoImpl

public T update(T object) {
    Session session = getSession();
    session.update(object);
    session.flush();
    return object;
}

希望对你有帮助

关于java - 保存成功后无法更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26350507/

相关文章:

Java 等效于 C++ 输出流重载

java - 如何使用 RecyclerView 创建滚动返回顶部按钮

java - Spring Hibernate getCurrentSession() 删除不工作

java - 为 servlet 分配异常 - JAVA 中的 Web 编程

c# - 如何将 SQL 的 'translate' 除了 (N)Hibernate (Criteria API)?

java - 与 Heroku 应用程序的直接 TCP 连接

java - Android java SELECT SQLite

Spring 3 请求映射 : Get path value

java - 外键没有默认值

java - Hibernate一对多关系数据插入报错