Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka
Abstract: This article is mainly about how to use Maven to build the spring+mybatis+mysql of the building example, the article is written in detail, there are pictures of the code, and finally with the effect of running.
First, the preparatory work
1. First create a table:
CREATE TABLE ' t_user ' ( ' user_id ' int (one) not null auto_increment, ' user_name ' char (+) NOT NULL, ' User_ PASSWORD ' char (TEN) NOT NULL, ' User_email ' char (+) NOT NULL, PRIMARY key (' user_id '), key ' Idx_name ' (' User_ NAME ')) Engine=innodb auto_increment=11 DEFAULT Charset=utf8
Insert some data casually:
INSERT into T_user (user_id, user_name, User_password, User_email) VALUES (1, ' Lin Bingwen ', ' [email protected] ', ' [EMAIL&NB Sp;protected] '); INSERT into T_user (user_id, user_name, User_password, User_email) VALUES (2, ' Evan ', ' 123 ', ' [email  ;p rotected]); 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  ;p rotected]); INSERT into T_user (user_id, user_name, User_password, User_email) VALUES (6, ' Little German ', ' yuh78 ', ' [email p Rotected] '); INSERT into T_user (user_id, user_name, User_password, User_email) VALUES (7, ' little ', ' cvff ', ' [Email prot Ected] '); INSERT into T_user (user_id, user_name, User_password, User_email) VALUES (8, ' home of the Forest ', ' gvv ', ' [Email protec Ted]); 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 (' Apple ', ' uih6 ', ' [email protected] ');
second, the project creation
1. Maven Project Creation
(1) New
(2) Select Quick Frame
(3) Output project name, package, remember to select the War (indicates a Web project, you can spingmvc to connect later)
(4) After the creation of a good
The directory is as follows:
(5) Check the
The three local JDK version must be the same!!!
Three, 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.0.xsd" >< Modelversion>4.0.0</modelversion><groupid>com.lin</groupid><artifactid>ssm_project </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 Pack 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 Spring Dependencies-- ><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 Dependency- -><dependency><groupid>junit</groupid><artifactid>junit</artifactid>< version>${junit.version}</version><scope>test</scope></dependency><!--log File Management Pack-- ><!--Log Start--><dependency><groupid>log4j</groupid><artifactid>log4j</ Artifactid><version>${log4j.version}</version></dependency><dependency><groupid >org.slf4j</groupid&gT;<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 dependency- ><dependency><groupid>org.springframework</groupid><artifactid>spring-test</ Artifactid><version>${spring.version}</version><scope>test</scope></dependency ><!--MyBatis Dependent--><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 pack--><dependency> <groupid>mysQl</groupid><artifactid>mysql-connector-java</artifactid><version>5.1.29</version ></dependency></dependencies></project>
3. Java code-------Src/main/java
The directory is as follows:
(1) User.java
The field of the table in the corresponding database, the package placed under Src/main/java Com.lin.domain
Package com.lin.domain;/** * User Mapping class * * @author Linbingwen * @time 2015.5.15 */public class User {private Integer use Rid;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;} @Overridepublic String toString () {return "User [userid=" + UserId + ", username=" + username+ ", userpassword=" + Userpas Sword + ", useremail=" + useremail+ "]";}}
(2) Userdao.java
The DAO interface class, which corresponds to the mapper file. The package Com.lin.dao is placed under the Src/main/java, the contents are as follows:
Package com.lin.dao;import com.lin.domain.user;/** * Feature summary: User's DAO class * * @author Linbingwen * @since September 28, 2015 */PUBL IC interface Userdao {/** * * @author Linbingwen * @since September 28, 2015 * @param userId * @return */public User selectuse Rbyid (Integer userId);}
(2) Userservice.java and Userserviceimpl.java
Service Interface class and implementation class, placed under Src/main/java package Com.lin.service, the contents are as follows:
Userservice.java
Package Com.lin.service;import Org.springframework.stereotype.service;import com.lin.domain.user;/** * Feature 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;/** * Feature Summary: UserService implementation class * * @author Linbingwen * @since September 28, 2015 */ @Servicepublic class Userserviceimpl Implements userservice{@Autowiredprivate Userdao userdao;public User Selectuserbyid (Integer userId) {return Userdao.selectuserbyid (userId);}}
(4) Mapper file
Used to correspond to DAO files, 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" ><!--setting field one by one for the domain class and table in the database, note the field names in the database fields and the domain class do not, here must! --><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 "jdbctype=" CHAR "/><result column=" User_email "property=" UserEmail " Jdbctype= "CHAR"/></resultmap><!--querying a single record--><select id= "Selectuserbyid" parametertype= "int" resultmap= "Baseresultmap" >select * from t_user WHERE user_id = #{userid}</select></mapper>
4. Resource allocation-------Src/main/resources
The directory is as follows:
(1) MyBatis configuration file
There's nothing here, because it's all put in the application.xml and placed under the MyBatis folder under Src/main/resources.
Mybatis-config.xml content 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
Under the Propertiesy folder under Src/main/resources
jdbc_driverclassname=com.mysql.jdbc.driverjdbc_url=jdbc:mysql://localhost:3306/learningjdbc_username=root[ Email protected]
(3) Spring configuration
This is the most important: the Application.xml content is as follows
<?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/schem A/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframewor K.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframe Work.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> < ;! --Introducing the JDBC configuration file--<bean id= "Propertyconfigurer" class= "Org.springframework.beans.factory.config.PropertyPlace Holderconfigurer "> <property name=" Locations "> <list> <value>classpat H:properties/*.properties</value> <!--If you have more than one profile, just continue adding it here--</list> </property> </bean> < !--Configuring the data source--><bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <!--do not 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= "[email protected]"/>-<!--using 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><!--automatically scans all xxxxmapper.xml corresponding Mapper interface files, so that you do not have to manually configure the Mpper mapping, as long as the Mapper interface class and mapper mapping file corresponding to it. --><bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" ><property name= "Basepackage" value = "Com.lin.dao"/></bean> <!--configuration MyBatis files, mapperlocations configuration * * Mapper.xml file location, configlocation configuration mybatis-config file location--><bean id= "Sqlsessionfactory" class= " Org.mybatis.spring.SqlSessionFactoryBean "><property name=" DataSource "ref=" DataSource "/> <property nam E= "Mapperlocations" value= "Classpath*:com/lin/mapper/**/*.xml"/> <property name= "configLocation" value= " Classpath:mybatis/mybatis-config.xml "/><!--<property name=" Typealiasespackage "value=" Com.tiantian.ckeditor.model "/>--></bean><!--automatic scanning of annotated bean--><context:component-scan Base-package= "Com.lin.service"/></beans>
(4) Log print log4j.properties
Just put it in src/main/resources.
log4j.rootlogger=debug,console,stdout#consolelog4j.appender.console= org.apache.log4j.consoleappenderlog4j.appender.console.layout= org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d [%t]%-5p [%c]-%m% nlog4j.logger.java.sql.resultset=infolog4j.logger.org.apache=infolog4j.logger.java.sql.connection= Debuglog4j.logger.java.sql.statement=debuglog4j.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
Iv. Unit Testing
The above configuration is intact, and then the test succeeds.
The entire directory is as follows:
(1) 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;/** * Function Summary: * * @author Linbingwen * @since September 28, 2015 *///specifies the bean injected configuration file @contextconfiguration (locations = {"Classpath:application.xml"})//using the standard JUnit @ Runwith note to tell JUnit to use the 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;/** * Function Summary: userservice unit Test * * @author Linbingwen * @since September 28, 2015 */public class Userservicetest extends springtestcase{@Autowiredprivate userservice userservice; Logger Logger = Logger.getlogger (userservicetest.class); @Testpublic void Selectuserbyidtest () {User user = Userservice.selectuserbyid (ten); Logger.debug ("Find results" + user);}}
Select Selectuserbyidtest, and then right-click to run the following
Output Result:
Results of important printing
Over here
2015-09-28 15:20:15,129 [main] DEBUG [com.lin.dao.UserDao.selectUserById]-==> preparing:select * from T_user WH ERE 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 [[email protected] ]2015-09-28 15:20:15,160 [main] DEBUG [Org.springframework.jdbc.datasource.DataSourceUtils]-returning JDBC Connection to Datasource2015-09-28 15:20:15,160 [main] DEBUG [com.lin.service.UserServiceTest]-Find results user [userid=10, Username=apple, USERPASSWORD=UIH6, [email protected]
Database:
The program runs successfully and the results are correct!
Copyright NOTICE: This article for Bo Master Lin Bingwen Evankaka original article, reproduced please indicate the source Http://blog.csdn.net/evankaka
Spring+mybatis+maven+mysql Construction Example