当前位置:网站首页>SSM integration
SSM integration
2022-07-07 08:28:00 【Bustling.】
SSM frame , namely Spring+SpringMVC+Mybatis, from Spring、MyBatis Integration of two open source frameworks (SpringMVC yes Spring Part of ). So far I'm interested in SSM The end of our study .
matters needing attention :
If Mybatis Medium mapper.xml And Mapper The interfaces have the same name and are located in java Contents and resources Under the package with the same name of the directory , that spring scanning Mapper Interface will automatically scan the same name Mapper.xml And assembly ;
If Mapper.xml And Mapper The interface does not have the same name or is not under the package with the same name , Must be in applicationContext.xml Middle configuration sessionFactory Of mapperLocations Property to specify mapper.xml The location of , here spring By identifying mapper.xml Of namespace To determine the corresponding Mapper Interface .
utilize Maven Build complete SSM project
One 、 Import coordinates to pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>finalSSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>finalSSM</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Two 、 database
In the target database account surface :
3、 ... and 、 Entity class
set The method is convenient Spring Inject
package Domain;
/*
Entity class
*/
public class Account {
private int id;
private String name;
private int money;
public int getId() {
return id;
}
public Account setId(int id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Account setName(String name) {
this.name = name;
return this;
}
public int getMoney() {
return money;
}
public Account setMoney(int money) {
this.money = money;
return this;
}
@Override
public String toString() {
return "account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
Four 、Mapper Interface
Try to be with mapper.xml With the same name and under the same name package
package Mapper;
import Domain.Account;
import java.util.List;
/*
mapper Interface
*/
public interface AccountMapper {
public void save(Account user);
public List<Account> findAll();
}
5、 ... and 、Service
Mainly for the interaction between the backend and the database
Interface :
package Service;
import Domain.Account;
import java.io.IOException;
import java.util.List;
public interface AccountService {
public void save(Account user) throws IOException;
public List<Account> findAll() throws IOException;
}
Realization :
package Service.Impl;
import Domain.Account;
import Mapper.AccountMapper;
import Service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*
The back end interacts with the database
*/
@Service("accountService")
public class serviceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public void save(Account user) throws IOException {
// Tradition Mybatis Method
/*InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
mapper.save(user);
sqlSession.commit();
sqlSession.close();*/
// Integration approach
accountMapper.save(user);
}
@Override
public List<Account> findAll() throws IOException {
//Mybatis Method
/*InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
List<Account> list = mapper.findAll();
sqlSession.commit();
sqlSession.close();
return list;*/
// Integration approach
return accountMapper.findAll();
}
}
6、 ... and 、Control
Mainly for SpringMVC Front end control of
package Control;
import Domain.Account;
import Service.AccountService;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
/*
front control
*/
@Controller
public class controller {
@Autowired
private AccountService accountService;// Point to serviceImpl
@RequestMapping( "/save")
@ResponseBody
public String save(Account a) throws IOException {
accountService.save(a);
return "success";
}
@RequestMapping("/findAll")
public ModelAndView findAll() throws IOException {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList",accountService.findAll());
modelAndView.setViewName("accountList");
return modelAndView;
}
}
7、 ... and 、Spring The configuration file
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: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">
<!--Spring-->
<!-- Component scan Annotations associated -->
<context:component-scan base-package="Service"/>
<context:component-scan base-package="Mapper"/>
<!-- Integrate Mybatis, take Session Creation and transaction management are entrusted to Spring control -->
<!-- load propeties file -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Configure data source information -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!-- To configure sessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- data source -->
<property name="dataSource" ref="dataSource"></property>
<!-- Alias -->
<property name="typeAliasesPackage" value="Domain"/>
<!-- scanning mapper.xml-->
<property name="mapperLocations" value="classpath*:Mapper/*.xml"/>
<!-- load Mybatis The configuration file -->
<!--<property name="configLocation" value="classpath:SqlMapConfig-spring.xml"></property>-->
</bean>
<!-- Instantiation mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--value by xml Package where the file is located -->
<property name="basePackage" value="Mapper"/>
</bean>
<!-- Be careful :
1. To configure sessionFactory when , Attributes other than data sources can be found in Mybatis Set... In the configuration file , But to load Mybatis The configuration file :
2. If Mapper.xml And Mapper.class Under the same package and with the same name ,spring scanning Mapper.class At the same time
Will automatically scan the same name Mapper.xml And assemble it to Mapper.class; If Mapper.xml And Mapper.class
Not under the same package or with the same name , You must configure properties mapperLocations To specify the mapper.xml The location of , here
spring By identifying mapper.xml Of namespace To determine the corresponding Mapper.class.
-->
<!-- Declarative transaction control -->
<!-- Platform transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- Configure transaction enhancements -->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- The transaction aop Weaving -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* Service.Impl.*.*(..))"/>
</aop:config>
</beans>
8、 ... and 、SpringMVC The configuration file
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--mvc Annotation driven -->
<mvc:annotation-driven>
<!-- Convert character encoding ,springmvc The default is ISO-8859-1 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="#{T(java.nio.charset.Charset).forName('UTF-8')}"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>applicaiton/javascript;charset=UTF-8</value>
</list>
</property>
<property name="writeAcceptCharset"><value>false</value></property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- controller Front end controller scanning -->
<context:component-scan base-package="Control">
<!-- Scan with Controller Annotated classes -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- Internal resource view parser -->
<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- Open static resource access -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!-- Profile upload parser -->
<!--<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!– Character set –>
<property name="defaultEncoding" value="UTF-8"/>
<!– file size /bit–>
<property name="maxUploadSize" value="500000"/>
</bean>-->
<!-- Configure interceptors -->
<!--<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/IV"/>
<bean class=""/>
</mvc:interceptor>
</mvc:interceptors>-->
<!-- Configure exception handler -->
<!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="/error.jsp"/>
<property name="exceptionMappings">
<map>
<entry key="java.lang.ClassCastException" value="/error.jsp"/>
<entry key="V_ exception handling . abnormal . Custom exception " value="/error.jsp"/>
</map>
</property>
</bean>-->
<!-- adopt HandlerAdapter Configuration mapper , You can use <mvc:annotation-driven> Instead of -->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>-->
</beans>
Nine 、Mybatis The configuration file
Mapper/AccountMapper.xml:
<?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="Mapper.AccountMapper">
<!-- Write mapping file -->
<!-- preservation -->
<select id="save" parameterType="account">
insert into account value (#{id},#{name},#{money})
</select>
<!-- Inquire about -->
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
SqlMapConfig.xml:
Integration can eliminate .
Ten 、 Other configuration files
jdbc.properties
log4j.properties
边栏推荐
- Wang Zijian: is the NFT of Tencent magic core worth buying?
- 漏洞复现-easy_tornado
- Ebpf cilium practice (2) - underlying network observability
- Vulnerability recurrence fastjson deserialization
- 使用BiSeNet实现自己的数据集
- Don't stop chasing the wind and the moon. Spring mountain is at the end of Pingwu
- Use of out covariance and in inversion in kotlin
- 在Rainbond中一键部署高可用 EMQX 集群
- The use of generics and vararg variable parameters in kotlin
- 【雅思口语】安娜口语学习记录 Part2
猜你喜欢
[quick start of Digital IC Verification] 11. Introduction to Verilog testbench (VTB)
Splunk子查询模糊匹配csv中字段值为*
Iptables' state module (FTP service exercise)
使用BiSeNet实现自己的数据集
Ebpf cilium practice (1) - team based network isolation
BiSeNet的特点
Application of slip ring of shipborne radar antenna
Improve the delivery efficiency of enterprise products (1) -- one click installation and upgrade of enterprise applications
[quick start of Digital IC Verification] 14. Basic syntax of SystemVerilog learning 1 (array, queue, structure, enumeration, string... Including practical exercises)
PVTV2--Pyramid Vision TransformerV2学习笔记
随机推荐
Le système mes est un choix nécessaire pour la production de l'entreprise
Easy to understand SSO
【Go ~ 0到1 】 第七天 获取时间戳,时间比较,时间格式转换,Sleep与定时器
Xcit learning notes
漏洞複現-Fastjson 反序列化
opencv学习笔记三——图像平滑/去噪处理
Wang Zijian: is the NFT of Tencent magic core worth buying?
2 - 3 arbre de recherche
拓维信息使用 Rainbond 的云原生落地实践
Interface as a parameter (interface callback)
Automatic upgrading of database structure in rainbow
Analyzing the influence of robot science and technology development concept on Social Research
IELTS review progress and method use [daily revision]
The use of generics and vararg variable parameters in kotlin
GFS分布式文件系统
Qinglong panel -- finishing usable scripts
Deit learning notes
漏洞复现-Fastjson 反序列化
Obsidan之数学公式的输入
[quick start of Digital IC Verification] 12. Introduction to SystemVerilog testbench (svtb)