java - 为什么 session.persist() 在我的程序中不起作用?

标签 java spring hibernate maven spring-mvc

我在我的Repository类中使用@Transactional(用@Repository注释)。我在我的类中做了一些插入操作并保存我使用session.persist()的数据。 但它在我的项目中不起作用。 我在其他项目中使用了相同的配置,并且坚持工作正常。[未使用相同的依赖项]。 以下是我的代码

这是我的 pom.xml

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>myownspring</groupId><artifactId>myownspring</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>3.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>3.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>4.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>4.1.4.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId> 

这是我的 ApplicationContext.xml

<beans 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"><mvc:annotation-driven/><!-- Configures the annotation-driven Spring MVC Controller programming model.
    Note that, with Spring 3.0, this tag works in Servlet MVC only!  --><mvc:resources location="/resources/" mapping="/resources/**"/><mvc:interceptors><bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"><property name="paramName" value="lang"/></bean></mvc:interceptors><bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"><property name="defaultLocale" value="en"/></bean><!-- Loading the resource 
    <import resource="hibernateContext.xml" /> --></beans>

这是我的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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 

            http://www.springframework.org/schema/beans/spring-beans-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/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- Declare a view resolver -->

<!-- Activates various annotations to be detected in bean classes -->
    <mvc:annotation-driven/>



<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
     For example @Controller and @Service. Make sure to set the correct base-package-->
<context:component-scan base-package="myownspring" />    

    <!-- view resolver for choosing view -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
         p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />


    <!-- Application Message Bundle -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>


    <context:property-placeholder location="classpath:hibernate.properties" />


     <!-- <bean id="multipartResolver"  
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />  
-->

    <import resource="hibernateContext.xml" />
</beans>

这是我的 hibernate.context.xml 文件

<beans xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd   http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.2.xsd   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"><!-- <context:property-placeholder location="/WEB-INF/config/hibernate.properties" /> --><!-- Enabling transaction annotiaon --><tx:annotation-driven/><!-- Defining the datasource using c3P0 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}" p:acquireIncrement="1" p:idleConnectionTestPeriod="30" p:maxIdleTime="3600" p:maxPoolSize="100" p:maxStatements="2" p:minPoolSize="20"/><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:packagesToScan="myownspring" p:dataSource-ref="dataSource"/><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" lazy-init="true"><property name="sessionFactory" ref="sessionFactory"/></bean></beans>

这是我的 web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <display-name>SEDI-Portal</display-name>

 <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/config/applicationContext.xml,
  /WEB-INF/config/spring-security.xml       </param-value>
 </context-param>

 <!-- For Spring Security -->

 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- Creates the Spring Container shared by all Servlets and Filters (loads context parameters)-->

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- Processes application requests -->

 <servlet>
  <servlet-name>DispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- not required if you have put servlet-name-servlet.xml in WEB-INF folder -->
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/config/DispatcherServlet-servlet.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>DispatcherServlet</servlet-name>
  <url-pattern>/AS/*</url-pattern>
 </servlet-mapping>


 <welcome-file-list>
  <welcome-file>/NewFile.html</welcome-file>
 </welcome-file-list>
</web-app>

这是我使用 @transactional 的类文件

package myownspring.daoimpl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import myownspring.dao.CrudUserDao;
import myownspring.model.User;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class CrudUserDaoImpl implements CrudUserDao {

    @Autowired
    SessionFactory sessionfactory;

    Session session;

    //@Override
    @Transactional
    public void createUser() {
        // TODO Auto-generated method stub
        session=sessionfactory.openSession();
        System.out.println("inside dao");
        User u=new User();
        u.setEmail("ff@ff.com");
        u.setPassword("gg");
        u.setRoleId(0);
        session.persist(u);
    }



}

这是我的模型类

package myownspring.model;

import java.io.Serializable;

import javax.persistence.*;

import org.hibernate.annotations.Generated;
import org.hibernate.validator.constraints.*;

 @Entity
 @Table(name="user")
public class User implements Serializable{

    private int id;
    private String email;
    private String password;
    private int roleId;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    @Column(name="username")
    @NotEmpty
    @Email
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name="password")
    @NotEmpty(message="not empty")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Column(name="contact")
    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }


}

感谢您的帮助

最佳答案

我认为 sessionfactory.openSession() 应该替换为 sessionfactory.getCurrentSession(),因为当前 session 是由 Spring 打开和管理的 session 。您打开另一个就绕过了 Spring 事务管理。

关于java - 为什么 session.persist() 在我的程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024038/

相关文章:

java - 在java中使用removeCharAt()的困难

java - 无法从迭代自然数的线程中打印所有数字

java - 扫描仪 nextLine Java 错误

java - 在 JPA @OneToMany 关系中更新 Set 元素的正确方法?

java - 当我修改 session 中的实体时,hibernate 如何检测到更改

java - 从模式窗口调用 Wicket setResponsePage() 时如何打败浏览器对话框弹出窗口?

java - Spring Security - 编码密码看起来不像 BCrypt

java - Spring 启动:scanBasePackages包含外部jar依赖项

java - 如何将 Elasticsearch 建议与 Spring 数据一起使用?

java - Hibernate 过滤器可以与条件查询一起使用吗?