Spring+Mybatis+Maven+MySql build example


http://blog.csdn.net/evankaka/article/details/48784641

1. Preparation

1. First create a table:

CREATE TABLE `t_user` (
  `USER_ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` char( 30) NOT NULL,
  `USER_PASSWORD` char(10) NOT NULL,
  `USER_EMAIL` char(30) NOT NULL,
  PRIMARY KEY (`USER_ID`),
  KEY `IDX_NAME` (`USER_NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8

Insert some data randomly:

INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (1, 'Lin Bingwen', '1234567@', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'evan', '123', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'kaka', 'cadg', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (4, 'simle', 'cscs', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (5, 'arthur', 'csas', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (6, '小德', 'yuh78', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (7, '小小', 'cvff', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (8, '林林之家', 'gvv', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (9, 'Lin Bingwen Evankaka', 'dfsc', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (10, 'apple', 'uih6', '[email protected]');



2. Project creation

1. Maven project creation

(1) New




(2) Select quick framework



(3) Output project name, package, remember to select war (representing web project, you can use spingMVC in the future)




(4) After creation, the

directory is as follows:




(5) Check that the JDK versions in

these three places must be the same! ! ! !










3. Sping+mybatis configuration

1. The entire project directory is as follows:




2. POM file

<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.
<modelVersion>4.0.0</modelVersion>
<groupId>com.lin</groupId>
<artifactId>ssm_project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- spring版本号 -->
<spring.version>3.2.8.RELEASE</spring.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<!-- junit版本号 -->
<junit.version>4.10</junit.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.1</mybatis.version>
</properties>

<dependencies>
<!-- 添加Spring依赖 -->
<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>

<!--单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>

<!-- 日志文件管理包 -->
<!-- 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单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

<!--mybatis依赖 -->
<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 driver package-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>

< /project>
3. The java code ------- src/main/java

directory is as follows:




(1) User.java

corresponds to the fields of the table in the database, and is placed in the package com.lin.domain under src/main/java

package com.lin.domain;

/**
* User mapping class
*
* @author linbingwen
* @time 2015.5.15
*/
public class User {
private Integer userId;
private String userName;
private String userPassword;
private String userEmail;

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserPassword() {
return userPassword;
}

public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}

public String getUserEmail() {
return userEmail;
}

public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName
+ ", userPassword=" + userPassword + ", userEmail=" + userEmail
+ "]";
}

}



(2) UserDao.java

Dao interface class, used to correspond to the mapper file. The package com.lin.dao placed under src/main/java has the following contents:

package com.lin.dao;


import com.lin.domain.User;

/**
* Function summary: User's DAO class
*
* @author linbingwen
*@since September 28, 2015
*/
public interface UserDao {
/**
*
* @author linbingwen
* @since September 28, 2015
* @param userId
* @return
*/
public User selectUserById(Integer userId);

}




(2) UserService.java and UserServiceImpl.java

service The interface class and implementation class are placed in the package com.lin.service under src/main/java, and the contents are as follows:

UserService.java


package com.lin.service;

import org.springframework.stereotype.Service;

import com.lin.domain .User;

/**
* Function summary: UserService interface class
*
* @author linbingwen
* @since September 28, 2015
*/
public interface UserService {
User selectUserById(Integer userId);

}


UserServiceImpl.java


package com.lin.service;

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

import com.lin.dao.UserDao;
import com.lin.domain.User;

/**
* 功能概要:UserService实现类
*
* @author linbingwen
* @since  2015年9月28日
*/
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;

public User selectUserById(Integer userId) {
return userDao.selectUserById(userId);

}

}


(4)mapper文件

Used to correspond to the dao file, placed under the com.lin.mapper package under src/main/java

<?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="com.lin.dao.UserDao">
<!--settings There is a one-to-one correspondence between the domain class and the fields of the table in the database. Note that the database fields and the field names in the domain class are not the same. It must be here! -->
<resultMap id="BaseResultMap" type="com.lin.domain.User">
<id column="USER_ID" property="userId" jdbcType="INTEGER" />
<result column="USER_NAME" property= "userName" jdbcType="CHAR" />
<result column="USER_PASSWORD" property="userPassword"



<select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
SELECT * FROM t_user WHERE USER_ID = #{userId}
</select>
</mapper>

4. Resource configuration-------src/ The main/resources

directory is as follows:




(1) mybatis configuration file

There is nothing here, because they are all placed in application.xml, and the

content of mybatis-config.xml in the mybatis folder under src/main/resources is as follows:


<?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>

(2) Data source configuration jdbc. properties

are placed in the propertiesy folder under src/main/resources


jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/learning
jdbc_username=root
jdbc_password=christmas258@
(3)Spring配置

这是最重要的: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 there are multiple configuration files, just keep adding them here-->
            </list>
        </property>
    </bean>
   
   

<!-- configure data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 不使用properties来配置 -->
<!-- <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@" /> -->
   <!-- 使用properties来配置 -->
<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>

<!-- Automatically scans all mapper interface files corresponding to XxxxMapper.xml, so that there is no need to manually configure the mapping of Mpper one by one, as long as The Mapper interface class corresponds to the Mapper mapping file. -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"
value="com.lin.dao" />
</bean>

    <!-- Configure Mybatis files, mapperLocations configure **Mapper.xml file location, configLocation configure mybatis-config file location -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource " />
        <property name="mapperLocations" value=" 

<!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
/> -->
</bean>

<!-- 自动扫描注解的bean -->
<context:component-scan base-package="com.lin.service" />

</beans>


(4)日志打印log4j.properties

就放在src/main/resources

log4j.rootLogger=DEBUG,Console,Stdout

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

log4j.appender.Stdout=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.Stdout.File=E://logs/log.log 
log4j.appender.Stdout.Append=true 
log4j.appender.Stdout.Threshold = DEBUG  
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout 
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 


Fourth, unit test The


above configuration is intact, and the next step is to test the success.

The whole directory is as follows:




(1) The test base class

package com.lin.baseTest;

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

/**
* Feature summary:
*
* @author linbingwen
* @since September 28, 2015
*/
/ /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 abstract class SpringTestCase extends AbstractJUnit4SpringContextTests {
protected Logger logger = LoggerFactory.getLogger(getClass());
}


(2) Test class

package com.lin.service;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.lin.baseTest.SpringTestCase;
import com.lin.domain.User;

/**
* Feature summary: UserService unit test
*
* @author linbingwen
*@since Sep 28, 2015
*/
public class UserServiceTest extends SpringTestCase {
@Autowired
private UserService userService;
Logger logger = Logger.getLogger(UserServiceTest.class);

@Test
public void selectUserByIdTest(){
User user = userService .selectUserById(10);
        logger.debug("Search result" + user);
}


}

Select selectUserByIdTest, then right click and run as follows







Output result:



Important printed result



here

2015-09-28 15:20:15,129 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==> Preparing: SELECT * FROM t_user WHERE USER_ID = ?
2015-09 -28 15:20:15,160 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==> Parameters: 10(Integer)
2015-09-28 15:20:15,160 [main] DEBUG [org.mybatis .spring.SqlSessionUtils] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6b64bff9]
2015-09-28 15:20:15,160 [main] DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
2015-09-28 15:20:15,160 [main] DEBUG [com.lin.service.UserServiceTest] - Find result User [userId=10, userName=apple, userPassword=uih6, userEmail=ff@ qq.com]

database:




The program runs successfully and the results are correct!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326757840&siteId=291194637