Spring+Spring MVC+Maven+Mybatis+MySQL Project Construction

Keywords: MySQL Spring Mybatis xml

This article describes in detail how to build a Spring+Spring MVC+Maven+Mybatis+MySQL project environment.
Installation and configuration of eclipse, maven and mysql are not discussed here for reference. Here.

Start building projects:
1.mysql database and table preparation:

CREATE TABLE `T_USER` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_type` tinyint(4) DEFAULT NULL COMMENT '0,System Management, 1. Business Administrator, 2. General Operator',
  `mobile` varchar(255) DEFAULT NULL COMMENT 'Administrator's mobile number',
  `is_biz_operator` tinyint(4) DEFAULT NULL COMMENT 'Is Business Operator 0: Not 1:Yes',
  `is_sys_operator` tinyint(4) DEFAULT NULL COMMENT 'Whether System Operator 0: Not 1:Yes',
  `login_name` varchar(255) NOT NULL COMMENT 'Employee Backstage Management Account',
  `real_name` varchar(100) DEFAULT NULL COMMENT 'User name',
  `password` varchar(255) NOT NULL COMMENT 'Employee Backstage Management Password',
  `status` tinyint(4) NOT NULL COMMENT 'Effective 0:Invalid 1:effective',
  `creator` bigint(20) DEFAULT NULL COMMENT 'creator',
  `updator` bigint(20) DEFAULT NULL COMMENT 'Reneer',
  `create_date` datetime DEFAULT NULL COMMENT 'Date of creation',
  `update_date` datetime DEFAULT NULL COMMENT 'Update date',
  `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0:No delete 1:delete',
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_login_name` (`login_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8;

2.maven Engineering Creation



After the completion of the new project, the catalogue structure of the project is as follows:

3. Edit the pom.xml file and add project package dependencies

<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>com.hy</groupId>
  <artifactId>ssm001</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <properties>
        <!-- spring version number -->
        <spring.version>3.2.8.RELEASE</spring.version>
        <!-- log4j Log File Management Package Version -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <!-- junit version number -->
        <junit.version>4.10</junit.version>
        <!-- mybatis version number -->
        <mybatis.version>3.2.1</mybatis.version>
  </properties>

  <dependencies>
        <!-- Add to Spring rely on -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</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-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</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>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--Unit test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Log File Management Package -->
        <!-- 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 -->

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

        <!--mybatis rely on -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!-- mybatis/spring package -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.0</version>
        </dependency>

        <!-- mysql Driving package -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
    </dependencies>
  
</project>

4. Configuration file initialization.
Initialize mybatis configuration file, database configuration file and Spring configuration file respectively.

Mybatis configuration file mybatis-config.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>    
</configuration>

Database configuration file jdbc.properties:

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://192.168.8.*:3306/db_user
jdbc_username=*
jdbc_password=*

spring configuration file application.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"
    xsi:schemaLocation="  
           http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
           http://www.springframework.org/schema/aop  
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     
     <!-- Introduce jdbc configuration file -->  
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               <value>classpath:properties/*.properties</value>
                <!--If you have more than one configuration file, just add it here. -->
            </list>
        </property>
    </bean>
    
    

    <!-- Configuring data sources -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- No use properties To configure -->
        <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
            <property name="url" value="jdbc:mysql://localhost:3306/learning" /> 
            <property name="username" value="root" /> 
            <property name="password" value="christmas258@" /> -->
       <!-- Use properties To configure -->
        <property name="driverClassName">
            <value>${jdbc_driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc_url}</value>
        </property>
        <property name="username">
            <value>${jdbc_username}</value>
        </property>
        <property name="password">
            <value>${jdbc_password}</value>
        </property>
    </bean>

    <!-- Automatic scanning of all XxxxMapper.xml Corresponding mapper Interface files, so you don't have to configure them manually one by one Mpper It maps, as long as Mapper Interface class and Mapper Mapping files can be matched. -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"
            value="com.hy.dao" />
    </bean>

    <!-- To configure Mybatis Documents, mapperLocations To configure**Mapper.xml File location, configLocation To configure mybatis-config file location-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!-- <property name="mapperLocations" value="com.hy.mapper"/> -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
        <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" 
            /> -->
    </bean>

    <!-- Automatic Scanning Annotation bean -->
    <context:component-scan base-package="com.hy.service" />

</beans>

5.mybatis reverse code generation
MyBatis belongs to a semi-automatic ORM framework. Because handwritten Mapping mapping files are easy to make mistakes, MyBatis generators can be used to automatically generate entity classes, DAO interfaces and Mapping mapping files. There are two ways:
The first way is to install the eclipse mybatis generator plug-in and use it to generate code.
May refer to Here.
The second way is to use the command mode of mybatis-generator.jar package directly.
The second approach is used in this demo. The mybatis generator configuration file generatorConfig.xm reads as follows:

<?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>  
<!-- Database Driver-->  
    <classPathEntry  location="mysql-connector-java-5.1.29.jar"/>  
    <context id="DB2Tables"  targetRuntime="MyBatis3">  
        <commentGenerator>  
            <property name="suppressDate" value="true"/>  
            <!-- Whether to remove automatically generated comments true: Yes, false:no -->  
            <property name="suppressAllComments" value="true"/>  
        </commentGenerator>  
        <!--Database Links URL,User name, password -->  
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.8.234:3306/db_user" userId="leaf" password="123456">  
        </jdbcConnection>  
        <javaTypeResolver>  
            <property name="forceBigDecimals" value="false"/>  
        </javaTypeResolver>  
        <!-- Package name and location of the generated model-->  
        <javaModelGenerator targetPackage="com.hy.domain" targetProject="../../java">  
            <property name="enableSubPackages" value="true"/>  
            <property name="trimStrings" value="true"/>  
        </javaModelGenerator>  
        <!-- Generate the package name and location of the mapping file-->  
        <sqlMapGenerator targetPackage="mapper" targetProject="../../resources">  
            <property name="enableSubPackages" value="true"/>  
        </sqlMapGenerator>  
        <!-- generate DAO The package name and location of-->  
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hy.dao" targetProject="../../java">  
            <property name="enableSubPackages" value="true"/>  
        </javaClientGenerator>  
        <!-- Tables to be generated tableName Is the table name or view name in the database domainObjectName Is the entity class name-->  
        <table tableName="T_USER" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>  
</generatorConfiguration>  
cd: G:\javaSpace\ssm001\src\main\resources\mybatis-generator
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite

After executing the above commands, mybatis-related codes are generated in the project directory, including entity classes, DAO interfaces and Mapping files.

6. Interface declaration and Implementation
Declare a UserService interface:

package com.hy.service;

import com.hy.domain.User;

public interface UserService {
    User getUserById(Long id);
}

Create a new class UserService Impl and implement the UserService interface:

package com.hy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hy.dao.UserMapper;
import com.hy.domain.User;
import com.hy.service.UserService;

@Service
public class UserServiceImpl implements UserService{
    
    @Autowired  
    private UserMapper userMapper;
    
    public User getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

}

7. Unit testing
Unit testing is to validate the getUserById method of the UserService interface in step 6.
A new class SpringTestCase.java is added to com.hy.baseTest, which implements unit testing using Spring JUnit 4 ClassRunner:

package com.hy.baseTest;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


//Specify the configuration file for bean injection  
@ContextConfiguration(locations = { "classpath:application.xml" })  
//Use the standard JUnit@RunWith annotation to tell JUnit to use Spring TestRunner  
@RunWith(SpringJUnit4ClassRunner.class)  
public class SpringTestCase extends AbstractJUnit4SpringContextTests {

}

Add the UserServiceTest class file in com.hy.test:

package com.hy.test;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.hy.baseTest.SpringTestCase;
import com.hy.domain.User;
import com.hy.service.UserService;

public class UserServiceTest extends SpringTestCase {

    @Autowired  
    private UserService userService; 

    @Test  
    public void selectUserByIdTest(){  
        User user = userService.getUserById((long) 1);
        System.out.println("userLoginName:" + user.getLoginName());
    }  
}

Run unit tests: User Service Test right-click Run As -> Junit Test, run results:

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
userLoginName:admin

So far, we have built a Spring+Maven+Mybatis+Mysql project environment. Many Spring-related technologies, such as automatic injection of annotations @Service, @Autowired, and Spring configuration files, are used for reference.
http://www.cnblogs.com/szlbm/...

Posted by NoMansLand on Thu, 13 Dec 2018 03:30:08 -0800