项目源码:https://github.com/dillyant/JAVA/tree/master/springmybatis
准备环境: mysql数据库,测试数据库yanwftest
数据准备:
CREATE TABLE `user_t` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(40) NOT NULL,
`password` varchar(255) NOT NULL,
`age` int(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user_t` VALUES ('1', '测试', 'sfasgfaf', '24');
1.创建maven项目 File->New->Maven Project
![](https://i-blog.csdnimg.cn/blog_migrate/9a7fbc0f00feb5765a3ad1b299a33a6f.png)
选择 maven-archetype-quickstart
![](https://i-blog.csdnimg.cn/blog_migrate/8741825e15fa14a0fce196452b5da92f.png)
填写Group Id,Artifact Id
![](https://i-blog.csdnimg.cn/blog_migrate/e1f730c55e13fc05890da93600c85a48.png)
创建之后目录结构如下:
![](https://i-blog.csdnimg.cn/blog_migrate/d3d704181961782fd4fd25d0439cadec.png)
2.自定义配置项目,选中当前项目右键,Java Build Path->Libraries,选择JRE ->Edit
![](https://i-blog.csdnimg.cn/blog_migrate/fa17c2a473502f2b45bbe5938cc600e2.png)
修改jre为Workspace default JRE。
![](https://i-blog.csdnimg.cn/blog_migrate/fa79cfa29ccdfdef7aaead222c14dcc0.png)
选中当前项目右键,New->Source Folder,创建src/main/resources
![](https://i-blog.csdnimg.cn/blog_migrate/4027fb20cfacdc4e2d23e176c75fcf68.png)
自定义之后的项目结构如下:
![](https://i-blog.csdnimg.cn/blog_migrate/124c56a84d69c69d33367e3598df3345.png)
3.修改pom.xml,如下
<
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.dillyant
</
groupId
>
<
artifactId
>
mavenspringmybatis
</
artifactId
>
<
version
>
0.0.1-SNAPSHOT
</
version
>
<
packaging
>
jar
</
packaging
>
<
name
>
mavenspringmybatis
</
name
>
<
url
>
http://maven.apache.org
</
url
>
<
properties
>
<
project.build.sourceEncoding
>
UTF-8
</
project.build.sourceEncoding
>
<
java.version
>
1.8
</
java.version
>
<
spring.version
>
4.3.10.RELEASE
</
spring.version
>
<
mybatis.version
>
3.4.4
</
mybatis.version
>
<
log4j.version
>
1.2.17
</
log4j.version
>
</
properties
>
<
dependencies
>
<
dependency
>
<
groupId
>
junit
</
groupId
>
<
artifactId
>
junit
</
artifactId
>
<
version
>
3.8.1
</
version
>
<
scope
>
test
</
scope
>
</
dependency
>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<
dependency
>
<
groupId
>
commons-logging
</
groupId
>
<
artifactId
>
commons-logging
</
artifactId
>
<
version
>
1.2
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-core
</
artifactId
>
<
version
>
${spring.version}
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-oxm
</
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-aop
</
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-test
</
artifactId
>
<
version
>
${spring.version}
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.mybatis
</
groupId
>
<
artifactId
>
mybatis
</
artifactId
>
<
version
>
${mybatis.version}
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.mybatis
</
groupId
>
<
artifactId
>
mybatis-spring
</
artifactId
>
<
version
>
1.3.1
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
mysql
</
groupId
>
<
artifactId
>
mysql-connector-java
</
artifactId
>
<
version
>
5.1.43
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
log4j
</
groupId
>
<
artifactId
>
log4j
</
artifactId
>
<
version
>
${log4j.version}
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
com.alibaba
</
groupId
>
<
artifactId
>
fastjson
</
artifactId
>
<
version
>
1.1.41
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
commons-dbcp
</
groupId
>
<
artifactId
>
commons-dbcp
</
artifactId
>
<
version
>
1.4
</
version
>
</
dependency
>
</
dependencies
>
<
build
>
<
plugins
>
<
plugin
>
<
groupId
>
org.apache.maven.plugins
</
groupId
>
<
artifactId
>
maven-compiler-plugin
</
artifactId
>
<
version
>
2.3.2
</
version
>
<
configuration
>
<
source
>
1.8
</
source
>
<
target
>
1.8
</
target
>
</
configuration
>
</
plugin
>
<
plugin
>
<
groupId
>
org.apache.maven.plugins
</
groupId
>
<
artifactId
>
maven-shade-plugin
</
artifactId
>
<
version
>
2.4.1
</
version
>
<
executions
>
<
execution
>
<
phase
>
package
</
phase
>
<
goals
>
<
goal
>
shade
</
goal
>
</
goals
>
<
configuration
>
<
transformers
>
<
transformer
implementation
=
"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"
>
<
mainClass
>
com.dillyant.mavenspringmybatis.App
</
mainClass
>
</
transformer
>
<
transformer
implementation
=
"org.apache.maven.plugins.shade.resource.AppendingTransformer"
>
<
resource
>
spring-mybatis.xml
</
resource
>
</
transformer
>
<
transformer
implementation
=
"org.apache.maven.plugins.shade.resource.AppendingTransformer"
>
<
resource
>
META-INF/spring.handlers
</
resource
>
</
transformer
>
<
transformer
implementation
=
"org.apache.maven.plugins.shade.resource.AppendingTransformer"
>
<
resource
>
META-INF/spring.schemas
</
resource
>
</
transformer
>
</
transformers
>
</
configuration
>
</
execution
>
</
executions
>
</
plugin
>
</
plugins
>
<
resources
>
<
resource
>
<
directory
>
src/main/java
</
directory
>
<
includes
>
<
include
>
**/*.xml
</
include
>
</
includes
>
</
resource
>
<
resource
>
<
directory
>
src/main/resources
</
directory
>
<
includes
>
<
include
>
**.*
</
include
>
</
includes
>
</
resource
>
</
resources
>
</
build
>
</
project
>
更新maven,右键项目maven->update project...
4.添加jar包目录结构如下
![](https://i-blog.csdnimg.cn/blog_migrate/d5d0a265038a4e50d7bb5adab13e3db1.png)
5.添加源码
包名:com.dillyant.model
类文件名:User.java
package
com.dillyant.model;
public
class
User {
private
Integer
id
;
private
String
userName
;
private
String
password
;
private
Integer
age
;
public
Integer getId() {
return
id
;
}
public
void
setId(Integer
id
) {
this
.
id
=
id
;
}
public
String getUserName() {
return
userName
;
}
public
void
setUserName(String
userName
) {
this
.
userName
=
userName
==
null
?
null
:
userName
.trim();
}
public
String getPassword() {
return
password
;
}
public
void
setPassword(String
password
) {
this
.
password
=
password
==
null
?
null
:
password
.trim();
}
public
Integer getAge() {
return
age
;
}
public
void
setAge(Integer
age
) {
this
.
age
=
age
;
}
}
包名:com.dillyant.dao
类文件名:UserMapper.java
package
com.dillyant.dao;
import
com.dillyant.model.User;
public
interface
UserMapper {
User selectByPrimaryKey(Integer
id
);
}
包名:
com.dillyant.dao
XML文件名:UserMapper.xml
<?
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.dillyant.dao.UserMapper"
>
<
select
id
=
"selectByPrimaryKey"
parameterType
=
"java.lang.Integer"
resultType
=
"com.dillyant.model.User"
>
select
id, user_name, password, age
from user_t
where id =
#{id,jdbcType=INTEGER}
</
select
>
</
mapper
>
包名:
com.dillyant.service
类文件名:IUserService.java
package
com.dillyant.service;
import
com.dillyant.model.User;
public
interface
IUserService {
public
User getUserById(
int
userId
);
}
包名:
com.dillyant.service.impl
类文件名:UserServiceImpl.java
package com.dillyant.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dillyant.dao.UserMapper;
import com.dillyant.model.User;
import com.dillyant.service.IUserService;
@Service
(
"userService"
)
@Transactional(readOnly=false)
public class UserServiceImpl implements IUserService {
@Resource
private UserMapper userMapper;
@Override
public User getUserById(int userId) {
return this.userMapper.selectByPrimaryKey(userId);
}
}
包名:
com.dillyant.mavenspringmybatis
类文件名:App.java
package
com.dillyant.mavenspringmybatis;
import
org.apache.log4j.Logger;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
com.alibaba.fastjson.JSON;
import
com.dillyant.model.User;
import
com.dillyant.service.impl.UserServiceImpl;
/**
* Hello world!
*
*/
public
class
App {
private
static
Logger
logger
= Logger.getLogger(App.
class
);
private
static
ApplicationContext
ac
;
public
static
void
main(String[]
args
) {
System.
out
.println(
"Hello World!"
);
ac
=
new
ClassPathXmlApplicationContext(
"spring-mybatis.xml"
);
UserServiceImpl
iuser
= (UserServiceImpl)
ac
.getBean(
"userService"
);
User
user
=
iuser
.getUserById(1);
logger
.info(JSON.toJSONString(
user
));
}
}
6 resources目录下添加配置文件
目录结构如下:
![](https://i-blog.csdnimg.cn/blog_migrate/094042c494c8e1723603be9b4a1587e3.png)
数据库配置文件jdbc.properties
jdbc.driver=
com.mysql.jdbc.Driver
jdbc.url=
jdbc:mysql://127.0.0.1:3306/yanwftest
jdbc.username=test
jdbc.password=
test
#定义初始连接数
jdbc.initialSize=
0
#定义最大连接数
jdbc.maxActive=
20
#定义最大空闲
jdbc.maxIdle=
20
#定义最小空闲
jdbc.minIdle=
1
#定义最长等待时间
jdbc.maxWait=
60000
日志配置文件 log4j.properties
#定义LOG输出级别
log4j.rootLogger=
debug,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=
org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=
System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout =
org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=
[%c]
-
%m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File =
org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File =
logs/sm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize =
10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold =
ALL
log4j.appender.File.layout =
org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =
[%p]
[%d{yyyy-MM-dd
HH\:mm\:ss}][%c]%m%n
spring mybatis集成配置文件 spring-mybatis.xml
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<
beans
xmlns
=
"http://www.springframework.org/schema/beans"
xmlns:aop
=
"http://www.springframework.org/schema/aop"
xmlns:tx
=
"http://www.springframework.org/schema/tx"
xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns:mybatis
=
"http://mybatis.org/schema/mybatis-spring"
xmlns:context
=
"http://www.springframework.org/schema/context"
xsi:schemaLocation
=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd"
>
<!-- 自动扫描 -->
<
context:component-scan
base-package
=
"com.dillyant.service.impl"
/>
<!-- 引入配置文件 -->
<
context:property-placeholder
location
=
"classpath:jdbc.properties"
system-properties-mode
=
"FALLBACK"
/>
<
bean
id
=
"dataSource"
class
=
"org.apache.commons.dbcp.BasicDataSource"
destroy-method
=
"close"
>
<
property
name
=
"driverClassName"
value
=
"${jdbc.driver}"
/>
<
property
name
=
"url"
value
=
"${jdbc.url}"
/>
<
property
name
=
"username"
value
=
"${jdbc.username}"
/>
<
property
name
=
"password"
value
=
"${jdbc.password}"
/>
<!-- 初始化连接大小 -->
<
property
name
=
"initialSize"
value
=
"${jdbc.initialSize}"
></
property
>
<!-- 连接池最大数量 -->
<
property
name
=
"maxActive"
value
=
"${jdbc.maxActive}"
></
property
>
<!-- 连接池最大空闲 -->
<
property
name
=
"maxIdle"
value
=
"${jdbc.maxIdle}"
></
property
>
<!-- 连接池最小空闲 -->
<
property
name
=
"minIdle"
value
=
"${jdbc.minIdle}"
></
property
>
<!-- 获取连接最大等待时间 -->
<
property
name
=
"maxWait"
value
=
"${jdbc.maxWait}"
></
property
>
</
bean
>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<
bean
id
=
"sqlSessionFactory"
class
=
"org.mybatis.spring.SqlSessionFactoryBean"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
/>
<!-- 自动扫描mapping.xml文件 -->
<
property
name
=
"mapperLocations"
value
=
"classpath:com/dillyant/dao/*.xml"
></
property
>
</
bean
>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<
bean
class
=
"org.mybatis.spring.mapper.MapperScannerConfigurer"
>
<
property
name
=
"basePackage"
value
=
"com.dillyant.dao"
/>
<
property
name
=
"sqlSessionFactoryBeanName"
value
=
"sqlSessionFactory"
></
property
>
</
bean
>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<
bean
id
=
"transactionManager"
class
=
"org.springframework.jdbc.datasource.DataSourceTransactionManager"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
/>
</
bean
>
<!-- 在Spring中使用基于注解的事务管理特性 -->
<
tx:annotation-driven
transaction-manager
=
"transactionManager"
proxy-target-class
=
"true"
/>
</
beans
>
7.运行测试,通过。
![](https://i-blog.csdnimg.cn/blog_migrate/8cad5ef9c817d074c370a7f321bc8ccb.png)
8.使用maven插件打包,选择当前项目右键,Run As->Maven Build , Goals为 clean package,Run
![](https://i-blog.csdnimg.cn/blog_migrate/c74ba318cb00131611b1df7aa309530b.png)
生成的jar包如下
![](https://i-blog.csdnimg.cn/blog_migrate/a6ea413785f7e306e25dadf54206ad03.png)
9.可执行jar包运行如下:
![](https://i-blog.csdnimg.cn/blog_migrate/03cde88f5f10507d9b2a342a4ffa9e36.png)