求助:SSH整合无法进行增删改的问题

烂漫一生 提交于 2020-02-05 10:55:24

关于SSH整合后无法进行增删改操作的问题
各位大佬帮忙看看,我的后台是使用Spring, Spring MVC ,Hibernate整合的
spring.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:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--自动aop-->
    <!--<aop:aspectj-autoproxy />-->

    <!--开启注解-->
    <context:annotation-config />
    <context:component-scan base-package="com.shop.xiaoce" />




    <context:component-scan base-package="com.shop.xiaoce" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>

    <bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssh?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false" />
        <property name="username" value="root" />
        <property name="password" value="111...aaa" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan">
            <value>com.shop.xiaoce.model</value>
        </property>
        <!--配置hibernate相关属性-->
        <property name="hibernateProperties">
            <props>
                <!--数据库方言-->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <!--自动增长-->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!--显示sql-->
                <prop key="hibernate.show_sql">true</prop>

                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTemolate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

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

    <tx:annotation-driven transaction-manager="txManager" />

    <tx:advice id="txAdvice" transaction-manager="txManager">
    <!-- the transactional semantics... -->
        <tx:attributes>
        <!-- all methods starting with 'get' are read-only -->
            <!--<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        &lt;!&ndash; other methods use the default transaction settings (see below) &ndash;&gt;
            <tx:method name="add*" read-only="false" />-->
            <tx:method name="add*" propagation="REQUIRED" rollback-for="EXCEPTION" read-only="false" />
            <tx:method name="*" propagation="REQUIRED" read-only="false" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="fooServiceOperation" expression="execution(* com.shop.xiaoce.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
    </aop:config>
</beans>

DAO层方法:

package com.shop.xiaoce.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class BaseDao<T> implements IBaseDao<T> {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    public Session getSession(){
        return hibernateTemplate.getSessionFactory().openSession();
    }

    private Class<T> getCla(){
        return (Class<T>)(((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }

    @Override
    public void add(T t) {
        hibernateTemplate.save(t);
    }

    @Override
    public void update(T t) {
        hibernateTemplate.update(t);
    }

    @Override
    public T load(int id) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        return session.load(getCla(),id);
    }

    @Override
    public List<T> list(String hql) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        List<T> list = query.list();
        return list;
    }

    @Override
    public List<T> list(String hql, Object[] params) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        if (params != null && params.length>0){
            for (int i=0;i<params.length;i++){
                query.setParameter(i,params[i]);
            }
        }
        return query.list();
    }

    @Override
    public List<T> list(String hql, Object[] params, int pageIndex, int pageSize) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        if (params != null && params.length>0){
            for (int i = 0;i <params.length;i++){
                query.setParameter(i,params[i]);
            }
        }
        return query.setFirstResult((pageIndex-1)*pageSize).setMaxResults(pageSize).list();
    }

    @Override
    public Long count(String hql) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        return (Long)session.createQuery(hql).uniqueResult();
    }

    @Override
    public Long count(String hql, Object[] params) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        if (params != null && params.length>0){
            for (int i = 0;i <params.length;i++){
                query.setParameter(i,params[i]);
            }
        }
        return (Long) query.uniqueResult();
    }
}

Service层方法:

package com.shop.xiaoce.service;

import com.shop.xiaoce.dao.ICommodityDao;
import com.shop.xiaoce.model.Commodity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CommodityService implements ICommodityService {

    @Autowired
    private ICommodityDao commodityDao;

    @Override
    public void add(Commodity commodity) {
        commodityDao.add(commodity);
    }

    @Override
    public Commodity load(int id) {
        return commodityDao.load(id);
    }

    @Override
    public List<Commodity> list(Integer[] user_id) {
        return commodityDao.list("from Commodity c where c.user.id=?0 and isActive='Y'",user_id);
    }

    @Override
    public List<Commodity> list(Integer[] user_id, int pageIndex, int pageSize) {
        return commodityDao.list("from Commodity c where c.user.id=?0 and isActive='Y'",user_id,pageIndex,pageSize);
    }

    @Override
    public List<Commodity> list(Object[] c_name,int pageIndex,int pageSize){
        return commodityDao.list("from Commodity c where c.user.id=?0 and (c.c_name like ?1 or c.house.id=?1) and isActive='Y'",c_name,pageIndex,pageSize);
    }

    @Override
    public List<Commodity> list(Object[] c_name) {
        return commodityDao.list("from Commodity c where c.user.id=?0 and (c.c_name like ?1 or c.house.id=?1) and isActive='Y'",c_name);
    }

    @Override
    public List<Commodity> listbyHouse(Object[] house_id, int pageIndex, int pageSize) {
        return commodityDao.list("from Commodity c where c.user.id=?0 and c.house.id=?1 and isActive='Y'",house_id,pageIndex,pageSize);
    }

    @Override
    public List<Commodity> listbyHouse(Object[] house_id) {
        return commodityDao.list("from Commodity c where c.user.id=?0 and c.house.id=?1 and isActive='Y'",house_id);
    }

    @Override
    public void delCommodity(Commodity commodity){
        commodityDao.update(commodity);
    }
}

Controller层方法:

package com.shop.xiaoce.controller;

import com.alibaba.fastjson.JSONObject;
import com.shop.xiaoce.model.Commodity;
import com.shop.xiaoce.model.StoreHouse;
import com.shop.xiaoce.model.User;
import com.shop.xiaoce.service.ICommodityService;
import com.shop.xiaoce.service.IStoreHouseService;
import com.shop.xiaoce.service.IUserService;
import com.sun.corba.se.impl.logging.POASystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CommodityController {

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private IStoreHouseService houseService;

    @RequestMapping("/commodity")
    @ResponseBody
    public JSONObject getCommodity(HttpSession session,int page,int limit){
        JSONObject jsonObject = new JSONObject();
        System.out.println("page:"+page+"   limit:"+limit);
        User user = (User) session.getAttribute("user");
        if (user == null){
            return null;
        }
        Integer[] userid = {user.getId()};
        int count = commodityService.list(userid).size();
        List<Commodity> list = commodityService.list(userid,page,limit);
        jsonObject.put("msg","success");
        jsonObject.put("code","0");
        jsonObject.put("count",count);
        jsonObject.put("data",list);
        return jsonObject;
    }

    @RequestMapping(value = "getCommoditybyName")
    @ResponseBody
    public  JSONObject getCommoditybyName(HttpSession session,String c_name,int page,int limit){
        System.out.println(c_name);
        User user = (User)session.getAttribute("user");
        Object[] obj = {user.getId(),"%"+c_name+"%"};
        List<Commodity> list = commodityService.list(obj,page,limit);
        int count = commodityService.list(obj).size();
        JSONObject respjson = new JSONObject();
        respjson.put("msg","success");
        respjson.put("code","0");
        respjson.put("count",count);
        respjson.put("data",list);
        return respjson;
    }

    @RequestMapping(value = "getCommoditybyHouse")
    @ResponseBody
    public JSONObject getCommoditybyHouse(HttpSession session,String house_id,int page,int limit){
        System.out.println("houseid:"+house_id);
        User user = (User)session.getAttribute("user");
        if (house_id.equals("")||house_id == null){
            return getCommodity(session,page,limit);
        }else {
            Object[] obj = {user.getId(),Integer.parseInt(house_id)};
            int count = commodityService.listbyHouse(obj).size();
            List<Commodity> list = commodityService.listbyHouse(obj,page,limit);
            JSONObject respjson = new JSONObject();
            respjson.put("msg","success");
            respjson.put("code","0");
            respjson.put("count",count);
            respjson.put("data",list);
            return respjson;
        }
    }

    @RequestMapping(value = "addCommodity",method = RequestMethod.POST)
    @ResponseBody
    public int addCommodity(HttpSession session,String c_name,String c_type,String c_sur,String c_house){
        int i = 0;
        StoreHouse house = houseService.load(Integer.parseInt(c_house));
        User user = (User) session.getAttribute("user");
        Commodity commodity = new Commodity(c_name,c_type,c_sur,house,user,"0","0","Y");
        commodityService.add(commodity);
        System.out.println("--------cname:"+c_name+",ctype:"+c_type+"---------");
        return i;
    }

    @RequestMapping(value = "delCommoditybyId",method = RequestMethod.POST)
    @ResponseBody
    public void delCommoditybyId(int id){
        Commodity commodity = commodityService.load(id);
        System.out.println(commodity+"isactive:"+commodity.getIsActive());
        commodityService.delCommodity(commodity);
    }
}

Enity层方法:

package com.shop.xiaoce.model;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;


//商品类
@Entity
@Table(name = "t_commodity")
public class Commodity {
    private int id;
    private String c_name;
    private String c_type;
    private String c_sur;  //数量
    private String c_out;
    private String c_in;
    private String isActive;
    private StoreHouse house;
    private User user;

    public Commodity(){
    }

    public Commodity(String c_name, String c_type,String c_sur, StoreHouse house,User user,String c_in,String c_out,String isActive) {
        this.c_name = c_name;
        this.c_type = c_type;
        this.house = house;
        this.user = user;
        this.c_sur = c_sur;
        this.c_in = c_in;
        this.c_out = c_out;
        this.isActive = isActive;
    }

    @Id
    @GenericGenerator(name = "c",strategy = "increment")
    @GeneratedValue(generator = "c")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getC_name() {
        return c_name;
    }

    public void setC_name(String c_name) {
        this.c_name = c_name;
    }

    public String getC_type() {
        return c_type;
    }

    public void setC_type(String c_type) {
        this.c_type = c_type;
    }

    public String getC_sur() {
        return c_sur;
    }

    public void setC_sur(String c_sur) {
        this.c_sur = c_sur;
    }

    public String getC_out() {
        return c_out;
    }

    public void setC_out(String c_out) {
        this.c_out = c_out;
    }

    public String getC_in() {
        return c_in;
    }

    public void setC_in(String c_in) {
        this.c_in = c_in;
    }

    public String getIsActive() {
        return isActive;
    }

    public void setIsActive(String isActive) {
        this.isActive = isActive;
    }

    @ManyToOne
    @JoinColumn(name = "user_id")
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @ManyToOne
    @JoinColumn(name = "house_id")
    public StoreHouse getHouse() {
        return house;
    }

    public void setHouse(StoreHouse house) {
        this.house = house;
    }

    @Override
    public String toString() {
        return "{" +
                "'id':'" + id +
                "', 'c_name':'" + c_name + '\'' +
                ", 'c_type':'" + c_type + '\'' +
                ", 'c_sur':'" + c_sur + '\'' +
                ", 'c_out':'" + c_out + '\'' +
                ", 'c_in':'" + c_in + '\'' +
                ", 'house':'"+house.getH_name()+
                "'}";
    }
}

我在进行保存时一直报只读错误,报错信息如下:

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
	at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1165)
	at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:643)
	at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:640)
	at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:359)
	at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:326)
	at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:640)
	at com.shop.xiaoce.dao.BaseDao.add(BaseDao.java:29)
	at com.shop.xiaoce.service.CommodityService.add(CommodityService.java:20)
	at com.shop.xiaoce.controller.CommodityController.addCommodity(CommodityController.java:93)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.orm.hibernate5.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:748)

尝试过各种方法都不行,用这个方法确实不报错了,但是数据库却无法插入hibernateTemplate.setCheckWriteOperations(false);

还请各位大神帮忙指导看看问题到底出在哪里了,跪谢!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!