主頁 > 區塊鏈 > Day26 SSM之整合(idea+maven),跟著敲,整合簡簡單單

Day26 SSM之整合(idea+maven),跟著敲,整合簡簡單單

2020-10-27 08:50:08 區塊鏈

ssm整合說明

(1)SSM是什么?
Spring,SpringMVC,Mybastis
(2)為什么要專門訓練SSM
要開發一個專案,首先是搭建SSM環境,之后才能開發其他功能
(3)整合思路是什么?
》》1.先搭建整合的環境
》》2.先把Spring的配置搭建完成
》》3.再使用Spring整合SpringMVC框架
》》4.最后使用Spring整合MyBatis框架
(4)SSM整合可以使用多種方式,咱們會選擇XML + 注解的方式
在這里插入圖片描述

一、SSM搭建環境

(1)資料庫創建ssm
(2)創建maven工程
(3)properties給誰用?
(4)依賴框架
(5)log4j

1、創建資料庫和表結構

create database ssm;
use ssm;
create table person(
id int primary key auto_increment, 
`name` varchar(20),
money double
);

2、創建maven工程

2.1 先創建一個父工程,之后在該工程里添加子模塊

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

2.2 整改一下父專案

在這里插入圖片描述

2.3 新建子模塊

在這里插入圖片描述
在這里插入圖片描述

2.4 整改子模塊

在這里插入圖片描述

3、子模塊中,匯入坐標并建立依賴

3.1 注意 MyBatis和 Spring的版本對應關系:

在這里插入圖片描述
pom.xml

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.2.9.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <!-- 表示開發的時候引入,發布的時候不會加載此包 -->
      <scope>test</scope>
    </dependency>
    
	<!-- 匯入Mysql資料庫鏈接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
	<!-- JSTL標簽類 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
	<!-- 日志檔案管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->

	<!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
	<!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

4、log4j加載組態檔

src\main\resources\log4j.properties
自已有需求,可以自行設定日志輸出級別日志存放位置

# Set root category priority to INFO and its only appender to CONSOLE.
# log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
# 可以把debug換成info,以免輸出很多debug資訊
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# 存放日志資訊的位置,可以不寫目錄,直接寫檔案名,就默認存在該模塊目錄下,
log4j.appender.LOGFILE.File=d:\ssm.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

5、撰寫物體類

src\main\java\cn\cyl\domain\Person.java

package cn.cyl.domain;

public class Person {
    private Integer id;
    private String name;
    private Double money;

    public Person() {
    }
    
    public Person(String name, Double money) {
        this.name = name;
        this.money = money;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getMoney() {
        return money;
    }
    public void setMoney(Double money) {
        this.money = money;
    }
}

6、撰寫業務層介面

src\main\java\cn\cyl\service\IPersonService.java

package cn.cyl.service;

import cn.cyl.domain.Person;
import java.util.List;

public interface IPersonService {
    //查詢所有用戶
    List<Person> findAll();

    //添加一個用戶
    void savePerson(Person person);

	//添加多個用戶
    void savePersons(List<Person> persons);
}

7、撰寫持久層介面

src\main\java\cn\cyl\dao\IPersonDao.java

package cn.cyl.dao;

import cn.cyl.domain.Person;
import java.util.List;

public interface IPersonDao {
    //查詢所有
    List<Person> findAll();

    //保存
    void savePerson(Person person);
}

搭建好后,如下圖

在這里插入圖片描述

二、保證Spring框架在web工程中獨立運行

1、第一步:撰寫spring組態檔并匯入約束

src\main\resources\applicationContext.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">

    <!--配置 spring 創建容器時要掃描的包,如:包下設定注解的 @Service @Repository @Component @AutoWried-->
    <context:component-scan base-package="cn.cyl">
        <!--制定掃包規則,不掃描 @Controller注解的JAVA類,其他的還是要掃描 -->
        <!--@Controller 注解的 JAVA 類是由springmvc來掃描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

2、第二步:使用注解配置業務層和持久層

src\main\java\cn\cyl\service\impl\PersonServiceImpl.java

/*  @Service("personService")
    IPersonService的實作類現在就一個,我們就不給它起id名了,*/
@Service
public class PersonServiceImpl implements IPersonService {

    @Autowired
    IPersonDao iPersonDao;

    @Override
    public List<Person> findAll() {
        List<Person> list = iPersonDao.findAll();
        return list;
    }

    @Override
    public void savePerson(Person person) {
        iPersonDao.save(person);
    }
    
    @Override
    public void savePersons(List<Person> persons) {
        for (int i = 0; i < persons.size(); i++) {
            //除0例外
            /*if (i==2){
                System.out.println(i/0);
            }*/
            iPersonDao.savePerson(persons.get(i));
        }
    }
}

src\main\java\cn\cyl\dao\impl\PersonDaoImpl.java

/*	整合Mybatis后,dao層功能由Mybatis完成,此注解就可以去掉了,不然會多個實作類
	然后后使用@Deprecated注解表示該類過時,不會再用了*/
@Repository
public class PersonDaoImpl implements IPersonDao {
    @Override
    public List<Person> findAll() {
        System.out.println("查詢所有    findAll Dao");
        //假資料庫
        List<Person> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person person = new Person("jack"+i,100.00);
            person.setId(i+1);
            list.add(person);
        }
        return list;
    }

    @Override
    public void savePerson(Person person) {
        System.out.println("保存  save Dao");
    }
}

3、第三步:測驗spring能否獨立運行

src\test\java\cn\cyl\service\TestPersonServiceImpl.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonServiceImpl {
    //創建日志類物件
    private static final Logger log = LoggerFactory.getLogger(TestPersonServiceImpl.class.getName());

    @Autowired
    IPersonService iPersonService;

    @Test
    public void test01(){//撰寫兩個業務功能 1.查找所有的person 2.保存一個person
        //呼叫 查詢方法
        log.info(iPersonService+"");
        List<Person> list = iPersonService.findAll();
        //呼叫 保存方法
        log.info(list+"");
        Person person = new Person("jack",100.00);
        iPersonService.savePerson(person);
    }
}

運行結果

在這里插入圖片描述

三、Spring整合SpringMVC

(1)web.xml中配置前端控制器DispatcherServlet
SpringMVC的核心就是DispatcherServlet,DispatcherServlet實質也是一個HttpServlet,DispatcherSevlet負責將請求分發,所有的請求都有經過它來統一分發,
(2)web.xml中配置編碼過濾器CharacterEncodingFilter
在 SpringMVC 中,框架直接給我們提供了一個用來解決請求和回應的亂碼問題的過濾器 CharacterEncodingFilter
(3)web.xml中配置編碼監聽器ContextLoaderListener
web.xml中的組態檔中ContextLoaderListener作為監聽器,會監聽web容器相關事件,在web容器啟動或者關閉時觸發執行回應程式

整合關鍵點就是:在web.xml中配置監聽器實作啟動服務創建容器
原理是:

1:Spring自動撰寫了一個監聽器,該監聽器監聽ServletContext物件的創建
2:一旦ServletContext創建時,會自動讀取contextConfigLocation配置,獲取核心組態檔applicationContext.xml
3:決議核心組態檔,根據包掃描器創建物件
4:將創建的物件存入Spring容器
5:將創建的Spring容器存入ServletContext域物件
之后我們需要做的事情:
1:從ServletContext域物件獲取Spring容器
2:從Spring容器中獲取想要的物件

1、第一步:在 web.xml中配置核心控制器(DispatcherServlet)、 編碼過濾器(CharacterEncodingFilter)、編碼監聽器(ContextLoaderListener)

src\main\webapp\WEB-INF\web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <!--設定spring組態檔的路徑及名稱-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--解決中文亂碼的過濾器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--背景關系監聽器,服務器部署完成后,該監聽器啟動,監聽ServletContext物件創建,
      自動裝配ApplicationContext.xml的配置資訊,然后將spring容器放到該ServletContext中快取起來
      配置Spring的監聽器,默認只加載WEB-INF目錄下的applicationContext.xml組態檔-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置前端控制器 controller-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加載springmvc.xml
      init-param  是DispatcherServlet的初始化引數,指定springmvc的路徑及檔案名稱
      當該Servlet 運行,springmvc的組態檔也會被加載進來-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--設定servlet的啟動加載時機
    load-on-startup  是servlet的加載時機, 1-5值,取值越小,加載時機越早-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

2、第二步:撰寫 SpringMVC 的組態檔

springmvc中配置視圖決議器,組件掃描,注解驅動,配置springmvc對資源檔案的放行,

src\main\resources\springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置創建 spring 容器要掃描的包 -->
    <context:component-scan base-package="cn.cyl">
        <!-- 制定掃包規則 ,只掃描使用@Controller 注解的 JAVA 類 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置的視圖決議器物件-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前綴-->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <!--后綴-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--過濾靜態資源   .js .css png-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--配置處理器映射器和處理器配接器 -->
    <!--開啟SpringMVC注解的支持 @RequestMapping @RequestBody @ResponseBody-->
    <mvc:annotation-driven/>
</beans>

3、第三步:撰寫 Controller 和 jsp 頁面

src\main\java\cn\cyl\controller\PersonController.java

@Controller
@RequestMapping("/person")
public class PersonController {

    private static final Logger log = LoggerFactory.getLogger(PersonController.class);

    @Autowired
    IPersonService iPersonService;

    @RequestMapping(path = "/list",method = RequestMethod.GET)
    public String list(Model model){
        List<Person> list = iPersonService.findAll();
        log.info("所有資訊 list :"+list);

        model.addAttribute("list",list);
        return "list";
    }
}

src\main\webapp\WEB-INF\pages\list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1px" width="100%">
    <c:forEach items="${list}" var="person">
        <tr>
            <td>${person.id}</td>
            <td>${person.name}</td>
            <td>${person.money}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

運行結果

在這里插入圖片描述
在這里插入圖片描述

四、保證 MyBatis 框架在 web 工程中獨立運行

1、第一步:撰寫 SqlMapConfig 組態檔

src\main\resources\SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--加載資料庫常量組態檔-->
    <properties resource="db.properties"/>

    <!--該包下的類起別名-->
    <typeAliases>
        <package name="cn.cyl.domain"/>
    </typeAliases>

    <!--配置mybatis的開發環境,該目錄下可以有多個environment,
    	和spring整合后 environments配置將廢除-->
    <environments default="mysql"><!--當前默認選擇的是mysql環境-->
        <!--配置mysql的環境-->
        <environment id="mysql">
            <!--配置事務的型別:jdbc事務管理-->
            <transactionManager type="JDBC"/>
            <!--配置連接資料庫的資訊:用的是資料源(連接池)-->
            <dataSource type="POOLED">
                <!--四大配置資訊-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--配置多個映射檔案,告知mybatis映射配置的位置-->
    <mappers>
        <package name="cn.cyl.dao"/>
    </mappers>
</configuration>

資料庫常量組態檔的內容
src\main\resources\db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=

2、第二步:撰寫 IPersonDao 映射組態檔

注意:我們使用代理 dao的方式來操作持久層,所以之前寫的Dao的實作類 PersonDaoImpl 就是多余的了,

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.cyl.dao.IPersonDao">
    <select id="findAll" resultType="person">
            select * from person
    </select>

    <insert id="savePerson" parameterType="person">
        insert into person (name,money)values(#{name},#{money})
    </insert>
</mapper>

3、第三步:測驗運行結果

public class TestMyBatis {

    private SqlSession session;

    @Before
    public void init(){
        //加載組態檔
        InputStream in = TestMyBatis.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        // 創建SqlSessionFactory物件
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 創建SqlSession物件
        session = factory.openSession();
    }

    @After
    public void destory(){
        session.commit();
        session.close();
    }

    @Test
    public void test01(){
        IPersonDao dao =  session.getMapper(IPersonDao.class);
        dao.savePerson(new Person("tony",200.00));
    }

    @Test
    public void test02(){
        IPersonDao dao =  session.getMapper(IPersonDao.class);
        List<Person> list = dao.findAll();
        System.out.println(list);
    }
}

運行結果

在這里插入圖片描述
在這里插入圖片描述

五、Spring整合MyBatis框架

整合思路

把 mybatis 組態檔(SqlMapConfig.xml)中內容配置到 spring 組態檔中,同時,把 mybatis 組態檔的內容清掉,也可以不清,

Spring整合MyBatis需要添加整合包

什么是mybatis-spring

MyBatis-Spring 會幫助你將 MyBatis 代碼無縫地整合到 Spring 中,它將允許 MyBatis 參與到 Spring 的事務管理之中,創建映射器 mapper 和 SqlSession 并注入到 bean 中,
以后就不需要呼叫 session.getMapper(IpersonDao.class)
session.commit()
session.close()

pom.xml

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

1、第一步:將SqlMapConfig.xml的資料配置到spring中

src\main\resources\applicationContext.xml

	<!--加載資料庫常量組態檔-->
    <context:property-placeholder location="classpath:db.properties" />

    <!--配置資料源連接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crud"/>
        <property name="user" value="root"/>
        <property name="password" value=""/>
    </bean>

    <!-- 配置 MyBatis 的 Session 工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 資料庫連接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!--起別名-->
        <property name="typeAliasesPackage" value="cn.cyl.domain"/>
    </bean>

    <!-- MapperScannerConfigurer 配置自動掃描所有 Mapper 介面和檔案,
        然后查找類路徑下的映射器并自動將它們創建成MapperFactoryBean,
        MapperFactoryBean生成這些介面的代理類,并注入到應用程式中-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--掃描這個包下面所有的介面和映射檔案-->
        <property name="basePackage" value="cn.cyl.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

2、第二步:配置 spring 的事務

src\main\resources\applicationContext.xml

<!--配置Spring框架宣告式事務管理-->
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP增強-->
    <aop:config>
        <aop:pointcut id="service" expression="execution(* cn.cyl.service.impl.*ServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
    </aop:config>

測驗

src\test\java\cn\cyl\service\TestPersonServiceImpl.java

@Test
    public void test02(){
        List<Person> list = new ArrayList<>();
        list.add(new Person("jack",100.00));
        list.add(new Person("rose",200.00));
        list.add(new Person("tony",300.00));
        iPersonService.savePersons(list);
    }

運行結果

在這里插入圖片描述

在業務層方法中添加例外(在添加第三個資料之前,報除0例外)

@Override
    public void savePersons(List<Person> persons) {
        for (int i = 0; i < persons.size(); i++) {
            //除0例外
            if (i==2){
                System.out.println(i/0);
            }
            iPersonDao.savePerson(persons.get(i));
        }
    }

運行結果

在這里插入圖片描述
添加資料失敗
在這里插入圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/193321.html

標籤:區塊鏈

上一篇:java圖形登錄界面設計

下一篇:java尋找迷宮路徑的簡單實作

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • JAVA使用 web3j 進行token轉賬

    最近新學習了下區塊鏈這方面的知識,所學不多,給大家分享下。 # 1. 關于web3j web3j是一個高度模塊化,反應性,型別安全的Java和Android庫,用于與智能合約配合并與以太坊網路上的客戶端(節點)集成。 # 2. 準備作業 jdk版本1.8 引入maven <dependency> < ......

    uj5u.com 2020-09-10 03:03:06 more
  • 以太坊智能合約開發框架Truffle

    前言 部署智能合約有多種方式,命令列的瀏覽器的渠道都有,但往往跟我們程式員的風格不太相符,因為我們習慣了在IDE里寫了代碼然后打包運行看效果。 雖然現在IDE中已經存在了Solidity插件,可以撰寫智能合約,但是部署智能合約卻要另走他路,沒辦法進行一個快捷的部署與測驗。 如果團隊管理的區塊節點多、 ......

    uj5u.com 2020-09-10 03:03:12 more
  • 谷歌二次驗證碼成為區塊鏈專用安全碼,你怎么看?

    前言 谷歌身份驗證器,前些年大家都比較陌生,但隨著國內互聯網安全的加強,它越來越多地出現在大家的視野中。 比較廣泛接觸的人群是國際3A游戲愛好者,游戲盜號現象嚴重+國外賬號安全應用廣泛,這類游戲一般都會要求用戶系結名為“兩步驗證”、“雙重驗證”等,平臺一般都推薦用谷歌身份驗證器。 后來區塊鏈業務風靡 ......

    uj5u.com 2020-09-10 03:03:17 more
  • 密碼學DAY1

    目錄 ##1.1 密碼學基本概念 密碼在我們的生活中有著重要的作用,那么密碼究竟來自何方,為何會產生呢? 密碼學是網路安全、資訊安全、區塊鏈等產品的基礎,常見的非對稱加密、對稱加密、散列函式等,都屬于密碼學范疇。 密碼學有數千年的歷史,從最開始的替換法到如今的非對稱加密演算法,經歷了古典密碼學,近代密 ......

    uj5u.com 2020-09-10 03:03:50 more
  • 密碼學DAY1_02

    目錄 ##1.1 ASCII編碼 ASCII(American Standard Code for Information Interchange,美國資訊交換標準代碼)是基于拉丁字母的一套電腦編碼系統,主要用于顯示現代英語和其他西歐語言。它是現今最通用的單位元組編碼系統,并等同于國際標準ISO/IE ......

    uj5u.com 2020-09-10 03:04:50 more
  • 密碼學DAY2

    ##1.1 加密模式 加密模式:https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html ECB ECB : Electronic codebook, 電子密碼本. 需要加密的訊息按照塊密碼的塊大小被分為數個塊,并對每個塊進 ......

    uj5u.com 2020-09-10 03:05:42 more
  • NTP時鐘服務器的特點(京準電子)

    NTP時鐘服務器的特點(京準電子) NTP時鐘服務器的特點(京準電子) 京準電子官V——ahjzsz 首先對時間同步進行了背景介紹,然后討論了不同的時間同步網路技術,最后指出了建立全球或區域時間同步網存在的問題。 一、概 述 在通信領域,“同步”概念是指頻率的同步,即網路各個節點的時鐘頻率和相位同步 ......

    uj5u.com 2020-09-10 03:05:47 more
  • 標準化考場時鐘同步系統推進智能化校園建設

    標準化考場時鐘同步系統推進智能化校園建設 標準化考場時鐘同步系統推進智能化校園建設 安徽京準電子科技官微——ahjzsz 一、背景概述隨著教育事業的快速發展,學校建設如雨后春筍,隨之而來的學校教育、管理、安全方面的問題成了學校管理人員面臨的最大的挑戰,這些問題同時也是學生家長所擔心的。為了讓學生有更 ......

    uj5u.com 2020-09-10 03:05:51 more
  • 位元幣入門

    引言 位元幣基本結構 位元幣基礎知識 1)哈希演算法 2)非對稱加密技術 3)數字簽名 4)MerkleTree 5)哪有位元幣,有的是UTXO 6)位元幣挖礦與共識 7)區塊驗證(共識) 總結 引言 上一篇我們已經知道了什么是區塊鏈,此篇說一下區塊鏈的第一個應用——位元幣。其實先有位元幣,后有的區塊 ......

    uj5u.com 2020-09-10 03:06:15 more
  • 北斗對時服務器(北斗對時設備)電力系統應用

    北斗對時服務器(北斗對時設備)電力系統應用 北斗對時服務器(北斗對時設備)電力系統應用 京準電子科技官微(ahjzsz) 中國北斗衛星導航系統(英文名稱:BeiDou Navigation Satellite System,簡稱BDS),因為是目前世界范圍內唯一可以大面積提供免費定位服務的系統,所以 ......

    uj5u.com 2020-09-10 03:06:20 more
最新发布
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:46:47 more
  • Hyperledger Fabric 使用 CouchDB 和復雜智能合約開發

    在上個實驗中,我們已經實作了簡單智能合約實作及客戶端開發,但該實驗中智能合約只有基礎的增刪改查功能,且其中的資料管理功能與傳統 MySQL 比相差甚遠。本文將在前面實驗的基礎上,將 Hyperledger Fabric 的默認資料庫支持 LevelDB 改為 CouchDB 模式,以實作更復雜的資料... ......

    uj5u.com 2023-04-16 07:28:31 more
  • .NET Core 波場鏈離線簽名、廣播交易(發送 TRX和USDT)筆記

    Get Started NuGet You can run the following command to install the Tron.Wallet.Net in your project. PM> Install-Package Tron.Wallet.Net 配置 public reco ......

    uj5u.com 2023-04-14 08:08:00 more
  • DKP 黑客分析——不正確的代幣對比率計算

    概述: 2023 年 2 月 8 日,針對 DKP 協議的閃電貸攻擊導致該協議的用戶損失了 8 萬美元,因為 execute() 函式取決于 USDT-DKP 對中兩種代幣的余額比率。 智能合約黑客概述: 攻擊者的交易:0x0c850f,0x2d31 攻擊者地址:0xF38 利用合同:0xf34ad ......

    uj5u.com 2023-04-07 07:46:09 more
  • Defi開發簡介

    Defi開發簡介 介紹 Defi是去中心化金融的縮寫, 是一項旨在利用區塊鏈技術和智能合約創建更加開放,可訪問和透明的金融體系的運動. 這與傳統金融形成鮮明對比,傳統金融通常由少數大型銀行和金融機構控制 在Defi的世界里,用戶可以直接從他們的電腦或移動設備上訪問廣泛的金融服務,而不需要像銀行或者信 ......

    uj5u.com 2023-04-05 08:01:34 more
  • solidity簡單的ERC20代幣實作

    // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "hardhat/console.sol"; //ERC20 同質化代幣,每個代幣的本質或性質都是相同 //ETH 是原生代幣,它不是ERC20代幣, ......

    uj5u.com 2023-03-21 07:56:29 more
  • solidity 參考型別修飾符memory、calldata與storage 常量修飾符C

    在solidity語言中 參考型別修飾符(參考型別為存盤空間不固定的數值型別) memory、calldata與storage,它們只能修飾參考型別變數,比如字串、陣列、位元組等... memory 適用于方法傳參、返參或在方法體內使用,使用完就會清除掉,釋放記憶體 calldata 僅適用于方法傳參 ......

    uj5u.com 2023-03-08 07:57:54 more
  • solidity注解標簽

    在solidity語言中 注釋符為// 注解符為/* 內容*/ 或者 是 ///內容 注解中含有這幾個標簽給予我們使用 @title 一個應該描述合約/介面的標題 contract, library, interface @author 作者的名字 contract, library, interf ......

    uj5u.com 2023-03-08 07:57:49 more
  • 評價指標:相似度、GAS消耗

    【代碼注釋自動生成方法綜述】 這些評測指標主要來自機器翻譯和文本總結等研究領域,可以評估候選文本(即基于代碼注釋自動方法而生成)和參考文本(即基于手工方式而生成)的相似度. BLEU指標^[^?88^^?^]^:其全稱是bilingual evaluation understudy.該指標是最早用于 ......

    uj5u.com 2023-02-23 07:27:39 more
  • 基于NOSTR協議的“公有制”版本的Twitter,去中心化社交軟體Damus

    最近,一個幽靈,Web3的幽靈,在網路游蕩,它叫Damus,這玩意詮釋了什么叫做病毒式營銷,滑稽的是,一個Web3產品卻在Web2的產品鏈上瘋狂傳銷,各方大佬紛紛為其背書,到底發生了什么?Damus的葫蘆里,賣的是什么藥? 注冊和簡單實用 很少有什么產品在用戶注冊環節會有什么噱頭,但Damus確實出 ......

    uj5u.com 2023-02-05 06:48:39 more