Preface: I have recently gone through the SSM framework. In order to prevent forgetting to configure the SSM, I have recorded the SSM integration process
Build environment and version introduction
I use idea2017, Maven3.6.1, Spring 5.1.6.RELEASE, Mybatis 3.5.0
Create a JavaWeb project
The directory structure is as follows
Introduction of depend on
The pom.xml file below is a bit heavy, but it is really useful and recommended
<? 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 > cn. Kt < / groupId > < artifactId > SSM < / artifactId > The < version > 1.0 - the SNAPSHOT < / version > < build > < plugins > <! XML --> <plugin> <groupId>org.mybatis. Generator </groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.5 < / version > < configuration > < verbose >true</verbose>
<overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> <! <properties> <springVersion>5.1.6.RELEASE</springVersion> <mybatisVersion>3.5.0</mybatisVersion> </properties> <dependencies> <! -- Junit for unit testing --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <! -- Lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> <! --druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 8.0.15 < / version > < / dependency > <! - loglog4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4 j < / artifactId > < version > 1.2.16 < / version > < / dependency > <! <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> The < version > 2.6.11 < / version > < / dependency > <! Pagehelper </groupId> <artifactId> pageHelper </artifactId> The < version > 5.1.10 < / version > < / dependency > <! -- <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.12</version> </dependency> <! --mybatis-spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> The < version > 2.0.0 < / version > < / dependency > <! --mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatisVersion}</version> </dependency> <! --spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${springVersion}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> < version > 1.8.12 < / version > < / dependency > < / dependencies > < project >Copy the code
The configuration file
Mybatis -generator mybatis-generator mybatis-generator mybatis-generator mybatis-generator mybatis-generator mybatis-generator mybatis-generator mapper. XML
generatorConfig.xml
<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE generatorConfiguration PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <! -- Your database driver location --> <classPathEntry location="D: \ Maven \ localRepository/mysql/mysql - connector - Java \ 8.0.15 \ mysql connector - Java - 8.0.15. Jar"/>
<context id="mysqlgenerator" targetRuntime="MyBatis3"> <! -- do not generate comments --> <commentGenerator> < Property name="suppressAllComments" value="true"/> </commentGenerator> <! --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis? serverTimezone=GMT"
userId="root"
password="Your password"/ > <! --> <javaModelGenerator targetPackage="cn.kt.domain" targetProject="src/main/java"> <! -- Generate a layer of package based on the targetPackage according to the schema of the database, and put the generated classes under this package, default isfalse -->
<property name="enableSubPackages" value="true"/ > <! Set whether to call trim() on String fields in getter methods --> <property name="trimStrings" value="true"/> </javaModelGenerator> <! <sqlMapGenerator targetPackage="cn.kt.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/> </sqlMapGenerator> <! -- Specify the location where the DAO interface is generated, mapper interface --> <javaClientGeneratortype="XMLMAPPER" targetPackage="cn.kt.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/> </javaClientGenerator> <! -- table generates the corresponding DoaminObject --> <table tableName="student" domainObjectName="Student"/>
</context>
</generatorConfiguration>
Copy the code
Maven ->Plugins-> Mybatis – Generator
StudentExample is used to implement QBC (Query by Criteria) queries
db.properties
For database related properties, please add serverTimezone after the URL. It is recommended to write the property name as jdbc.driver jdbc.username
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis? serverTimezone=GMT%2B8&useSSL=falseName = root password = your password maxActive = 100 maxIdle = 50 initialSize = 20 timeBetweenEvictionRunsMillis = 60000 minEvictableIdleTimeMillis=300000Copy the code
applicationContext-mybatis.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> <settings> <! These are all optional --> <! Mapper. XML file --> <setting name="cacheEnabled" value="true"/ > <! - to enablelog4j-->
<setting name="logImpl" value="LOG4J"/ > <! --> <setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="lazyLoadTriggerMethods" value="clone"/> </settings> <plugins> <! <plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="pageSizeZero" value="true"/>
</plugin>
</plugins>
</configuration>
Copy the code
applicationContext-springmvc.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"> <! --< ! – Processor mapper & NDASH; > <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> < ! – Processor adapter & NDASH; > <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>-->
<!--等效于上面两个-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <! -- prefix --> <property name="prefix" value="/WEB-INF/jsp/"/ > <! -- suffix --> <property name="suffix" value=".jsp"/> </bean> <! --> <context:component-scan base-package="cn.kt"/>
</beans>
Copy the code
Applicationcontext.xml Spring main configuration file
<? 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"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.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"> <! --> <context:property-placeholder location="classpath:db.properties"/>
<context:component-scan base-package="cn.kt"></context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
<property name="driverClassName" value="${driver}"/ > <! -- Configure initial size, min, Max --> <property name="initialSize" value="${initialSize}"/>
<property name="minIdle" value="${maxIdle}"/>
<property name="maxActive" value="${maxActive}"/ > <! -- Set the timeout for waiting to get connections --> <property name="maxWait" value="60000"/ > <! -- Configure how often to check for idle connections to close, in milliseconds --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/ > <! -- Set the minimum time for a connection to live in the pool, in milliseconds --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/> </bean> <! Create SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <! -- Pool --> <property name="dataSource" ref="dataSource"/ > <! -- Scan mapper.xml configuration file --> <property name="mapperLocations" value="classpath:cn/kt/mapper/*.xml"/ > <! --> <property name="configLocation" value="classpath:applicationContext-mybatis.xml"/>
</bean>
<bean id="session" factory-bean="sqlSessionFactory" factory-method="openSession" scope="prototype"/>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.kt.mapper"/> </bean> <! -- Spring manages transactions --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Copy the code
web.xml
<? xml version="1.0" encoding="UTF-8"? > <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <! Encoding</filter-name> Encoding</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>Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! - the listener - > < listener > < listener - class > org. Springframework. Web. Context. ContextLoaderListener < / listener - class > < / listener > <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <! -- Prevent spring memory overflow listener --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>Copy the code
Ehcacahe. XML can be omitted if ehCache is not enabled in mybatis configuration file
<? xml version="1.0" encoding="UTF-8"? > <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <! -- Disk save path --> <diskStore path="F:/out/mybatis_cache"/>
<defaultCache
maxElementsInMemory="1"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
Copy the code
Log4j.properties, also not configured if not enabled
Set # # # # # #
log4j.rootLogger = ERROR ,stdout
log4j.logger.cn.kt.mapper=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Copy the code
If you want to add maven dependencies to a war package, you will find ClassNotFound bugs
test
Write a Controller
@Controller
public class MyController {
@Autowired
private MyService myService;
@RequestMapping("/test")
public ModelAndView controller(){
myService.service();
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("hello");
returnmodelAndView; }}Copy the code
A service
@Service
public class MyService {
@Autowired
StudentMapper studentMapper;
public void service(){ StudentExample studentExample=new StudentExample(); StudentExample.Criteria criteria1 = studentExample.createCriteria(); Criteria1. AndAgeBetween (1, 10); List<Student> list=studentMapper.selectByExample(studentExample); System.out.println(list); }}Copy the code
Enter the corresponding path in the address bar, http://localhost:8080/ project name /test service layer successfully query the data, output in the console
The browser is successfully displayed
Done!!