详解环境搭建SSM
1.概述:
SSM即为spring 4 +spring mvc +mybatis 3.4.6
推荐使用maven或者gradle 来配置 下面给出maven配置方式
2.项目结构:
新建web项目
这里要特别说一下:如果你安装eclipse spring插件可以利用插件来检查多次依赖包,没有安装插件的推荐安装
spring elements>>beans>>显示了你用的标签,过去你需要记忆方式,或者说循规蹈矩的排除bean,现在直接使用这个插件,可以看到你注解标签下拥有的bean数,可以很好解决问题
3.pom文件
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <groupId>com.gitee.dgwcode</groupId> 6 <artifactId>mybatis06_SSM</artifactId> 7 <version>0.0.1-SNAPSHOT</version> 8 9 <dependencies> 10 <dependency> 11 <groupId>org.slf4j</groupId> 12 <artifactId>slf4j-api</artifactId> 13 <version>1.7.25</version> 14 </dependency> 15 <dependency> 16 <groupId>org.slf4j</groupId> 17 <artifactId>slf4j-log4j12</artifactId> 18 <version>1.7.25</version> 19 <scope>test</scope> 20 </dependency> 21 22 <dependency> 23 <groupId>javax.servlet</groupId> 24 <artifactId>jstl</artifactId> 25 <version>1.2</version> 26 </dependency> 27 28 <!-- 连接池 --> 29 <dependency> 30 <groupId>com.mchange</groupId> 31 <artifactId>c3p0</artifactId> 32 <version>0.9.5.2</version> 33 </dependency> 34 <dependency> 35 <groupId>mysql</groupId> 36 <artifactId>mysql-connector-java</artifactId> 37 <version>5.1.39</version> 38 </dependency> 39 <!-- mybatis相关包 --> 40 <dependency> 41 <groupId>org.mybatis</groupId> 42 <artifactId>mybatis</artifactId> 43 <version>3.4.6</version> 44 </dependency> 45 <dependency> 46 <groupId>org.mybatis</groupId> 47 <artifactId>mybatis-spring</artifactId> 48 <version>1.3.2</version> 49 </dependency> 50 <!-- spring 相关的一律包 --> 51 <dependency> 52 <groupId>org.springframework</groupId> 53 <artifactId>spring-jdbc</artifactId> 54 <version>4.3.9.RELEASE</version> 55 </dependency> 56 57 <dependency> 58 <groupId>org.springframework</groupId> 59 <artifactId>spring-context</artifactId> 60 <version>4.3.9.RELEASE</version> 61 </dependency> 62 <dependency> 63 <groupId>org.springframework</groupId> 64 <artifactId>spring-web</artifactId> 65 <version>4.3.9.RELEASE</version> 66 </dependency> 67 <dependency> 68 <groupId>org.springframework</groupId> 69 <artifactId>spring-webmvc</artifactId> 70 <version>4.3.9.RELEASE</version> 71 </dependency> 72 <dependency> 73 <groupId>javax.servlet</groupId> 74 <artifactId>javax.servlet-api</artifactId> 75 <version>4.0.0-b07</version> 76 <scope>provided</scope> 77 </dependency> 78 <dependency> 79 <groupId>javax.servlet.jsp</groupId> 80 <artifactId>jsp-api</artifactId> 81 <version>2.2</version> 82 <scope>provided</scope> 83 </dependency> 84 </dependencies> 85 </project>
4.application
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" 7 xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 11 12 <!-- Spring希望管理所有的业务逻辑组件,等。。。 --> 13 <context:component-scan base-package="com.gitee.dgwcode"> 14 <context:exclude-filter type="annotation" 15 expression="org.springframework.stereotype.Controller" /> 16 <context:exclude-filter type="annotation" 17 expression="org.springframework.web.bind.annotation.ControllerAdvice" /> 18 </context:component-scan> 19 20 21 <!-- 引入数据库的配置文件 --> 22 <context:property-placeholder location="classpath:dbconfig.properties" /> 23 <context:property-placeholder location="classpath:dbconfig.properties" /> 24 <!-- Spring用来控制业务逻辑。数据源、事务控制、aop --> 25 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 26 <property name="jdbcUrl" value="${jdbc.url}"></property> 27 <property name="driverClass" value="${jdbc.driver}"></property> 28 <property name="user" value="${jdbc.username}"></property> 29 <property name="password" value="${jdbc.password}"></property> 30 <property name="initialPoolSize" value="10"></property> 31 <property name="maxIdleTime" value="30"></property> 32 <property name="maxPoolSize" value="100"></property> 33 <property name="minPoolSize" value="10"></property> 34 </bean> 35 36 <!-- spring事务管理 --> 37 <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 38 <property name="dataSource" ref="dataSource"></property> 39 </bean> 40 41 <!-- 开启基于注解的事务 --> 42 <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/> 43 44 <!--创建出SqlSessionFactory对象 --> 45 <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> 46 <property name="dataSource" ref="dataSource"></property> 47 <!-- configLocation指定全局配置文件的位置 --> 48 <property name="configLocation" value="classpath:mybatis-cfg.xml"></property> 49 <!--mapperLocations: 指定mapper文件的位置--> 50 <property name="mapperLocations" value="classpath*:mybatis/mapper/*.xml"></property> 51 </bean> 52 <!--配置一个可以进行批量执行的sqlSession 也可以配置sqlSessionTempplete --> 53 <!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 54 <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"></constructor-arg> 55 <constructor-arg name="executorType" value="BATCH"></constructor-arg> 56 </bean> --> 57 58 <!-- 扫描所有的mapper接口的实现,让这些mapper能够自动注入; 59 base-package:指定mapper接口的包名 60 --> 61 <mybatis-spring:scan base-package="com.gitee.dgwcode.mapper"/> 62 <!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 63 <property name="basePackage" value="com.atguigu.mybatis.dao"></property> 64 </bean> --> 65 66 </beans>
5:spring mvc .xml
这里你也可以选择在spring mvc 文件中配置事物,数据源,计划等
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 11 12 <context:component-scan 13 base-package="com.gitee.dgwcode" use-default-filters="false"> 14 <context:include-filter type="annotation" 15 expression="org.springframework.stereotype.Controller" /> 16 <context:include-filter type="annotation" 17 expression="org.springframework.web.bind.annotation.ControllerAdvice" /> 18 </context:component-scan> 19 20 <bean 21 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 22 <property name="prefix" value="/view/"></property> 23 <property name="suffix" value=".jsp"></property> 24 </bean> 25 26 <mvc:annotation-driven></mvc:annotation-driven> 27 <mvc:default-servlet-handler /> 28 29 30 </beans>
6:mybaits
SqlSessionFactoryBean 在sprinig代替了 SqlSessionFactoryBeanBuilde 所以原来的配置文件完全可以在spring的配置文件中进行,但是官方解释 配置属性是不完全的,那么你这里就要考虑是不是你要最基本的mybatis功能,还是说你要高度定制你自己的mybatis的各种
属性,所以你最好是保留这个配置文件
注意:我这个配置删除了一些无关配置,当前spring-mybat插件runing的时候也会忽略那么不需要的标签
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 8 <!-- 配置指定使用LOG4J输出日志 --> 9 <settings> 10 <setting name="logImpl" value="LOG4J" /> 11 <!-- 配置驼峰语法 --> 12 <setting name="mapUnderscoreToCamelCase" value="true" /> 13 <!-- 开启自动映射 --> 14 <!-- <setting name="autoMappingBehavior" value="NONE"/> --> 15 <!-- 懒加载 --> 16 <setting name="lazyLoadingEnabled" value="false" /> 17 <setting name="cacheEnabled" value="true"/> 18 </settings> 19 20 <!-- 配置包的别名,这样我们在mapper中定义时,就不需要使用类的全限定名称,只需要使用类名即可 :值 主要解决 在结果映射中 需要全路径的问题. 21 这个的包名: 是指 模型包名,也就是 对应结果实体类返回的名字. --> 22 <typeAliases> 23 </typeAliases> 24 25 <!-- 类型处理器,mybatis3.4以后jdk1.8实现ljsr310 就不要加入原来默认的配置了 --> 26 <typeHandlers> 27 <!-- <typeHandler handler=""/> --> 28 </typeHandlers> 29 30 <!-- 使用外部数据库配置的方式 读取规则是就近原则:先properties 里的 在外部文件 --> 31 <!-- <properties resource="dbconfig.properties"> <property name="username" 32 value="root"/> <property name="password" value="root"/> </properties> --> 33 34 35 <!-- 配置不同的数据库便于支持不同的数据, 在mapper通过 --> 36 <databaseIdProvider type="DB_VENDOR"> 37 <property name="MySQL" value="mysql" /> 38 <!-- <property name="SQL Server" value="sqlserver" /> <property name="DB2" 39 value="db2" /> <property name="Oracle" value="oracle" /> --> 40 </databaseIdProvider> 41 42 </configuration>
7:code文件
这里不贴出代码文件,其实就是实现一个最基本的crud,类如下图。
8:要说明的问题:
8.1:可能你已经习惯了Hihernate那套session使用方式,所以这里给出配置方式
在mybatis中对应的sqlSession,下面这段代码应该非常属性:
1 private SqlSessionFactory sqlsession; 2 3 @Before 4 public void setUp() throws IOException { 5 String path="mybatis.cfg.xml"; 6 InputStream stream = Resources.getResourceAsStream(path); 7 sqlsession= new SqlSessionFactoryBuilder().build(stream); 8 }
而对应的spring整合中,你只需要保证创建sqlSessionfactoryBean对象
1 <!--创建出SqlSessionFactory对象 --> 2 <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> 3 <property name="dataSource" ref="dataSource"></property> 4 <!-- configLocation指定全局配置文件的位置 --> 5 <property name="configLocation" value="classpath:mybatis-cfg.xml"></property> 6 <!--mapperLocations: 指定mapper文件的位置--> 7 <property name="mapperLocations" value="classpath*:mybatis/mapper/*.xml"></property> 8 </bean>
再想到hibernate 对应的factory,就有下面的注入方式
1 public class UserDaoImpl implements UserDao { 2 3 private SqlSession sqlSession; 4 5 public void setSqlSession(SqlSession sqlSession) { 6 this.sqlSession = sqlSession; 7 } 8 9 public User getUser(String userId) { 10 return (User) sqlSession.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); 11 } 12 }
保证文件配置了SqlSessionTemplate
1 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 2 <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"></constructor-arg> 3 <constructor-arg name="executorType" value="BATCH"></constructor-arg> 4 </bean>
8.2:hibernateDaoSupport对应支持
源码:
1 public abstract class SqlSessionDaoSupport extends DaoSupport { 2 3 private SqlSession sqlSession; 4 5 private boolean externalSqlSession; 6 7 public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { 8 if (!this.externalSqlSession) { 9 this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); 10 } 11 } 12 13 public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { 14 this.sqlSession = sqlSessionTemplate; 15 this.externalSqlSession = true; 16 } 17 18 /** 19 * Users should use this method to get a SqlSession to call its statement methods 20 * This is SqlSession is managed by spring. Users should not commit/rollback/close it 21 * because it will be automatically done. 22 * 23 * @return Spring managed thread safe SqlSession 24 */ 25 public SqlSession getSqlSession() { 26 return this.sqlSession; 27 } 28 29 /** 30 * {@inheritDoc} 31 */ 32 @Override 33 protected void checkDaoConfig() { 34 notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"); 35 } 36 37 }
sqlSeesionDaoSupport需要sqlseesiontemplate 或者sqlsessionfactoryBean的直接注入,所以:
1 @Repository 2 public class EmployeeDao extends SqlSessionDaoSupport { 3 4 5 @Autowired 6 public void setSqlSession(SqlSessionTemplate sqlSession) { 7 super.setSqlSessionTemplate(sqlSession); 8 } 9 public List<Employee> getEmps(){ 10 SqlSession session = getSqlSession(); 11 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 12 List<Employee> emps = mapper.getEmps(); 13 return emps; 14 } 15 16 }
1 public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { 2 public User getUser(String userId) { 3 return (User) getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); 4 } 5 }
这里你要确保你得appliacationContext.xml中具有sqlsessiontemplate才能保证注入:
其实你发现没有,EmployeeDao这么复杂,实际上你配置MapperScannerConfigurer 他内步完成的也是这些操作
1 @Service 2 public class EmployeeService { 3 4 @Autowired 5 private EmployeeMapper employeeMapper; 6 7 @Autowired 8 EmployeeDao employeeDao; 9 10 /*@Autowired 11 private SqlSession sqlSession;*/ 12 13 public List<Employee> getEmps() { 14 //List<Employee> selectOne = sqlSession.selectOne("com.gitee.dgwcode.mapper.EmployeeMapper.getEmps"); 15 //EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); 16 //List<Employee> emps = employeeDao.getEmps(); 17 return employeeMapper.getEmps(); 18 } 19 20 }