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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...