2018-04-19 13:40:43 557浏览
USerDao层实现类不要继承HibernateDaoSupport,现在Spring不推荐使用这种方式:使用Hibernate5.2.10.Final版本会报错。使用Hibernate5.1.0.Final版本则不会报错,总之推荐使用SessionFactory的方式来获取Session:
@Repository publicclassUserDaoImplimplementsUserDao{ @Autowired privateSessionFactorysessionFactory; @Override publicvoidadd(Stringusername){ //TODOAuto-generatedmethodstub //Stringsql="insertintouser(username)values(?)"; Useruser=newUser(); user.setUsername(username); Sessionsession=sessionFactory.getCurrentSession(); session.save(user); } }
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scanbase-package="com.servlet"></context:component-scan> <context:property-placeholderlocation="classpath:jdbc.properties"/> <!--配置C3p0连接池对象--> <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"> <propertyname="user"value="root"></property> <propertyname="password"value="root"></property> <propertyname="jdbcUrl"value="jdbc:mysql:///spring"></property> <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property> <propertyname="maxPoolSize"value="200"></property> <propertyname="initialPoolSize"value="20"></property> </bean> <!--配置SessionFactory--> <beanid="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!--引入数据源--> <propertyname="dataSource"ref="dataSource"></property> <propertyname="hibernateProperties"> <props> <propkey="hibernate.show_sql">true</prop> <propkey="hibernate.format_sql">true</prop> <propkey="hibernate.hbm2ddl.auto">update</prop> <propkey="hibernate.connection.isolation">4</prop> <!--<propkey="current_session_context_class">thread</prop> --></props> </property> <propertyname="packagesToScan"> <list> <value>com.servlet</value> </list> </property> </bean> <!--1.配置平台事务管理器 jdbc/Mybatis:DateSourceTransactionManager Hibernate:HibernateTransactionManager --> <beanid="transactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <propertyname="sessionFactory"ref="sessionFactory"></property> </bean> <!--开启事务注解--> <tx:annotation-driventransaction-manager="transactionManager"/> </beans>
【关注微信公众号获取更多学习资料】