ssh整合思想 Spring分模塊開發 crud參數傳遞 解決HTTP Status 500 - Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or(增加事務)

来源:https://www.cnblogs.com/qingyundian/archive/2018/01/06/8215419.html
-Advertisement-
Play Games

在Spring核心配置文件中沒有增加事務方法,導致以上問題 Action類UserAction UserService類 UserDao介面 UserDaoImplements類 User實體類: web.xml 自動啟動監聽和過濾器 Spring核心配置文件bean.xml 通過引入各個分模塊 分 ...


在Spring核心配置文件中沒有增加事務方法,導致以上問題

Action類UserAction

package com.swift.action;

import com.opensymphony.xwork2.ActionSupport;
import com.swift.service.UserService;

public class UserAction extends ActionSupport {
    private UserService userService;
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @Override
    public String execute() throws Exception {
        System.out.println("action..................");
        userService.add("fly","War of Mercenaries");
        userService.add("big-dog","War of Mercenaries");
        userService.add("ram","War of Mercenaries");
        userService.add("rabbit","War of Mercenaries");
        userService.add("hama","War of Mercenaries");
        userService.add("shiguan","War of Mercenaries");
        userService.update("ram","War of Mercenaries","公羊","傭兵的戰爭");
        userService.delete("rabbit","War of Mercenaries");
        userService.getOne(2);
        userService.findAll();
        userService.findYouWant("ram","War of Mercenaries");
        return NONE;
    }

}

UserService類

package com.swift.service;

import org.springframework.transaction.annotation.Transactional;

import com.swift.dao.UserDao;
@Transactional
public class UserService {

    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void add(String userName,String address) {
        System.out.println("UserService.................add");
        userDao.add(userName,address);
    }
    public void update(String userName,String address,String modifyName,String modifyAddress) {
        System.out.println("UserService.................update");
        userDao.update(userName,address,modifyName,modifyAddress);
    }
    public void delete(String userName,String address) {
        System.out.println("UserService.................delete");
        userDao.delete(userName,address);
    }
    public void getOne(int number) {
        System.out.println("UserService.................get the number of");
        userDao.getOne(number);
    }
    public void findAll() {
        System.out.println("UserService.................find all");
        userDao.findAll();
    }
    public void findYouWant(String userName,String address) {
        System.out.println("UserService.................find you want");
        userDao.findYouWant(userName,address);
    }
    
}

UserDao介面

package com.swift.dao;

public interface UserDao {
    public void add(String userName,String address);
    public void update(String userName,String address,String modifyName,String modifyAddress);
    public void delete(String userName,String address);
    public void getOne(int number);
    public void findAll();
    public void findYouWant(String userName,String address);
}

UserDaoImplements類

package com.swift.dao;

import java.util.List;

import org.springframework.orm.hibernate5.HibernateTemplate;

import com.swift.entity.User;

public class UserDaoImplements implements UserDao {
    private HibernateTemplate hibernateTemplate;
    private User user;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

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

    @Override
    public void add(String userName, String address) {
        // 增加
        user.setUsername(userName);
        user.setAddress(address);
        hibernateTemplate.save(user);
    }

    @Override
    public void update(String userName, String address, String modifyName, String modifyAddress) {
        List<User> list = (List<User>) hibernateTemplate.find("from User where userName=? and address=?", userName,
                address);
        if (list != null) {
            for (User user : list) {
                System.out.println(user.getUsername() + " :: " + user.getAddress());
                user.setUsername(modifyName);
                user.setAddress(modifyAddress);
                hibernateTemplate.update(user);
            }
        } else {
            System.out.println("您要更新的記錄不存在!!!!!");
        }
    }

    @Override
    public void delete(String userName, String address) {
        List<User> list = (List<User>) hibernateTemplate.find("from User where userName=? and address=?", userName,
                address);
        if (list != null) {
            for (User user : list) {
                System.out.println(user.getUsername() + " :: " + user.getAddress());
                hibernateTemplate.delete(user);
            }
        } else {
            System.out.println("您要刪除的記錄不存在!!!!!");
        }
    }

    @Override
    public void getOne(int number) {
        User user = hibernateTemplate.get(User.class, number);
        System.out.println(user.getUsername() + " :: " + user.getAddress());
    }

    @Override
    public void findAll() {
        List<User> list = (List<User>) hibernateTemplate.find("from User");
        for (User user : list) {
            System.out.println(user.getUsername() + " :: " + user.getAddress());
        }
    }

    @Override
    public void findYouWant(String userName, String address) {
        List<User> list = (List<User>) hibernateTemplate.find("from User where userName=? and address=?", userName,
                address);
        System.out.println(list.toString());
        for (User user : list) {
            System.out.println(user.getUsername() + " :: " + user.getAddress());
        }
    }

}

User實體類:

package com.swift.entity;

public class User {
    
    private Integer uid;
    private String username;
    private String address;
    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public User(String username, String address) {
        this.username = username;
        this.address = address;
    }
    public User(Integer uid, String username, String address) {
        this.uid = uid;
        this.username = username;
        this.address = address;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    
}

web.xml 自動啟動監聽和過濾器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>2018-01-03_Spring_Hibernate</display-name>
  
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:bean.xml</param-value>
  </context-param>
  
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <filter>
  <filter-name>struts2</filter-name>
  <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Spring核心配置文件bean.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: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">

    <!-- c3p0連接池得到dataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sw_database"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    
    <!-- 創建hibernate事務管理器 -->
    <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 啟動Hibernate事務管理器 -->
    <tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>
    
    <!-- 引入分模塊 -->
    <import resource="classpath:User.xml"/>
    
</beans>

分模塊User.xml 只負責Action部分

<?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: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">

    <bean id="userAction" class="com.swift.action.UserAction" scope="prototype">
    <property name="userService" ref="userService"></property>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!-- Hibernate核心配置文件沒有連接資料庫,所以需要註入 -->
    <property name="dataSource" ref="dataSource"></property>
    <!-- Hibernate核心配置文件的位置 -->
    <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
    </bean>
    
    <bean id="userService" class="com.swift.service.UserService">
    <property name="userDao" ref="userDaoImplements"></property>
    </bean>
    
    <bean id="userDaoImplements" class="com.swift.dao.UserDaoImplements">
    <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    <property name="user" ref="user"></property>
    </bean>
    
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
       <!-- 前一個sessionFactory是HibernateTemplate類內部的 -->
    <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <bean id="user" class="com.swift.entity.User"></bean>
    
</beans>

Hibernate核心配置文件hibernate.cfg.xml

<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC   
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"   
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
   <!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sw_database</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property> -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 方言的數字很重要一定找到該項目名的連接類 -->
        
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property><!-- 別處複製過來的代碼要重新在Eclipse中一點點輸入否則會出錯 -->
        
        <!-- create: 先刪表,再建表。 create-drop: 啟動時建表,退出前刪表。 update: 如果表結構不一致,就創建或更新。 
            validate: 啟動時驗證表結構,如果不致就拋異常。 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!--指定映射文件,可映射多個映射文件 -->
        <mapping resource="User.hbm.xml"></mapping>
    </session-factory>

</hibernate-configuration>

Hibernate映射文件

<?xml version="1.0" encoding='UTF-8'?>     
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- 實體類映射文件 -->
<hibernate-mapping>

    <class name="com.swift.entity.User" table="t_user">
        <!-- 主鍵 -->
        <id name="uid">
            <generator class="native"></generator>
        </id>
        <!-- 其他屬性 -->
        <property name="username"/>
        <property name="address"/>
    </class>
    
</hibernate-mapping>

struts2的Action配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
 
<struts>
    <package name="default" extends="struts-default" namespace="/">
    
    <!-- action的class不要寫全名會創建兩個對象,而寫Spring配置文件中id的內容,只建一個對象
                  前提有struts2-spring-plugin-2.3.4.1.jar -->
        
        <action name="userAction" class="userAction">
        </action>
    </package>
</struts>

瀏覽器操作

控制台顯示

 

 

資料庫顯示

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 期末,要交一個大作業,正巧之前跑國圖借書的時候,暈頭轉向的,國圖內居然沒有導航!!!借這個機會做一個室內導航的demo,只是半成品,還需要加入室內定位,匹配一下坐標才能在實際中使用。 demo:利用蜂鳥雲平臺進行二次開發實現。愛琴海商城內部尋徑。 主要功能: 代碼!不給~ 上圖!! 初始界面 查找終 ...
  • 定義求最大最小值的函數 輸入為: ...
  • 上面這段代碼一直在用,面試的時候也經常被問到,卻從未深究過,不知道線程池到底是怎麼回事,今天看看源代碼,一探其究竟 線程池主要控制的狀態是ctl,它是一個原子的整數,其包含兩個概念欄位: workerCount:有效的線程數量 runState:線程池的狀態 為了在一個整型值裡面包含這兩個欄位,我們 ...
  • 最近總是接觸時間處理問題,花了點時間整理以前使用過的方法,修改整合,記錄下來方便以後使用。 package cc.vvxtoys.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java ...
  • 一、異常處理 Spring提供了多種方式將異常轉換為響應: 特定的Spring異常將會自動映射為指定的HTTP狀態碼 在預設情況下,Spring會將自身的一些異常自動轉換為合適的狀態碼,從而反饋給客戶端。實際上,如果沒有出現任何映射的異常,響應都會帶有500狀態碼。映射表如下: 自定義異常上可以添加 ...
  • 一、Python簡介 1、Python創始人 Guido van Rassum, 於1989年,創立。 2、Python的主要應用領域 雲計算:openstack web 開發: 科學運算 AI 金融:量化交易、金融分析等 圖形GUI 語言的類型: 3、編程語言的類型 解釋型語言:容易移植 編譯型語 ...
  • 代碼以後再補 歐拉函數 我們用$\phi(n)$表示歐拉函數 定義:$\phi(n)$表示對於整數$n$,小於等於$n$中與$n$互質的數的個數 性質 1.$\phi(n)$為積性函數 2.$\sum_{d|n}\phi(d)=n$ 3.$1$到$n$中與$n$互質的數的和為$n*\dfrac{\p ...
  • 凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/ Question: Answer: ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...