小鸡炸

导航

SSM的集成

一、导入jar包

spring管理mybaitis的jar包官网:http://www.mybatis.org/spring/zh/index.html

maven依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
		<dependency>
		    <groupId>org.aspectj</groupId>
		    <artifactId>aspectjweaver</artifactId>
		    <version>1.6.12</version>
		</dependency>
		
			<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>   
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.6.0</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.6</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.3</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.9</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
		<dependency>
			<groupId>org.hibernate.validator</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>6.1.5.Final</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

2、在web.xml启动DispathcherServlet核心处理器

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
        	<param-name>contextConfigLocation</param-name>
        	<param-value>/WEB-INF/classes/springcore.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3、创建springcore.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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<mvc:annotation-driven/>
	<context:component-scan base-package="package"></context:component-scan>
	<!--1 引入属性文件,在配置中占位使用 -->
	<context:property-placeholder location="classpath:druid.properties" />

	<!--2 配置druid数据源 -->
	<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
		<!--驱动类名 -->
		<property name="driverClassName" value="${driver}" />
		<!-- url -->
		<property name="url" value="${url}" />
		<!-- 用户名 -->
		<property name="username" value="${uname}" />
		<!-- 密码 -->
		<property name="password" value="${password}" />
	</bean>

	<!--3 会话工厂bean sqlSessionFactoryBean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
				<!-- 数据源 -->
		<property name="dataSource" ref="datasource"></property>
		<!-- 别名 -->
		<property name="typeAliasesPackage" value="package.bean"></property>
 		<!--configLocation属性指定mybatis的核心配置文件 
 		<property name="configLocation" value="classpath:config.xml" />
 		--> 
		<!-- sql映射文件路径 -->
		<property name="mapperLocations" value="classpath*:package/mapper/*.xml"></property>
	</bean>

	<!-- 配置mybatis的sqlSession -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory" />
	</bean>
 	
 	<!--4 自动扫描对象关系映射 -->
	<bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 这里的basePackage 指定了dao层接口路劲,这里的dao接口不用自己实现 -->
		<property name="basePackage" value="package.dao" />
		<!-- 如果只有一个数据源的话可以不用指定,但是如果有多个数据源的话必须要指定 -->
		<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" 
			/> -->
		<!--直接指定了sqlsessionTemplate名称,这个和上面的其实是一样的  -->
		<property name="sqlSessionTemplateBeanName" value="sqlSession" />
	</bean>
	
	<!--定义事物管理器,由spring管理事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>
    <!--支持注解驱动的事务管理,指定事务管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
     <!--7 aspectj支持自动代理实现AOP功能 -->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

4、添加druid.properties和log4j配置

druid.properties配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://locahost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8
uname=root
password=123456
filters=stat
initialSize=2
maxActive=10
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=select CURRENT_DATE FROM dual
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
log4j配置
### 设置###
#log4j配置文件中路径配置一般有三种方法: 
#(1)绝对路径法:直接配置为系统觉得路径; 
#(2)相对路径法: 
#log4j.appender.logfile.File=../logs/app.log,将日志记录到tomcat下的logs文件夹; 
#log4j.appender.logfile.File=logs/app.log,将日志记录到tomcat的bin目录下的logs文件夹; 
#(3)使用环境变量相对路径法:程序会优先找jvm环境变量,然后再找系统环境变量,来查找配置文件中的变量。 
#log4j.appender.logfile.File=user.dir/logs/app.log,使用tomcat容器时user.dir/logs/app.log,使用tomcat容器时{user.dir}对应tomcat的bin目录; 
#log4j.appender.logfile.File=user.home/logs/app.log,user.home/logs/app.log,{user.home}对应操作系统当前用户目录; 
#log4j.appender.logfile.File=webApp.root/logs/app.log,webApp.root/logs/app.log,{webApp.root}对应当前应用根目录;

#log4j.rootLogger = debug,stdout,D,E
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = d://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =d://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

5、开始添加dao层代码

@Repository
public interface StudentDao {
	//既可以使用注解、亦可以使用配置两者结合使用
	@Select("select * from student")
	List<Student> getAll();
	
	List<Student> getAll2();
}

6、创建Dao层对应的Mapper.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="package.dao.StudentDao">
	<select id="getAll2" resultType="student">
		select * from student where classid=1
	</select>
</mapper>

7、在业务逻辑层添加事物注解

public interface StudentService {
	List<Student> getAll();
	
	List<Student> getAll2();
	
	int add(Student info);
}


@Service
//事物注解、下面所有方法、只要抛出异常就回滚,否则提交
@Transactional
public class StudentServiceImpl implements StudentService {
	@Autowired
	StudentDao dao;
	public List<Student> getAll() {
		return dao.getAll();
	}

	public List<Student> getAll2() {
		return dao.getAll2();
	}

	public int add(Student info) {
		//故意抛出一个异常,测试是否能回滚操作
		dao.add(info);
		dao.add(info);
		
		return 0;
	}
}

8、在Controller层调用Dao或者Service

@RestController
@RequestMapping("/student")
public class StudentConroller {
	@Autowired
	StudentService service;
	
	@RequestMapping("/show1")
	public Object show1() {
		return service.getAll();
	}
	
	@RequestMapping("/show2")
	public Object show2() {
		return service.getAll2();
	}
	
	@RequestMapping("/show3")
	public Object show3() {
		Student info=new Student(222, "test", "111", "1", 1, null);
		service.add(info);
		
		return service.getAll2();
	}
	
	@RequestMapping("/test001")
	public Object test001() {
		return "test00111111111111111111";
	}
}

posted on 2022-01-19 11:03  小鸡炸  阅读(29)  评论(0编辑  收藏  举报