❤️Spring从入门到大神--Spring整合MyBatis
Posted 一只楠喃
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了❤️Spring从入门到大神--Spring整合MyBatis相关的知识,希望对你有一定的参考价值。
Spring整合MyBatis
之前使用的持久层框架是MyBatis, 现在将Mybatis框架整合到Spring框架中,由Spring统一管理.其核心思路是把Mapper对应的实现类对象存放在IOC容器中.
整体思路:
1.按照原来的方式搭建Mybatis框架
2.按照原来的方式搭建Spring框架
3.把sqlMapConfig.xml和MyBatisUtils工具类替换成MyBatisConfig配置类
4.在SpringConfig配置类中做特定修改
需求: 通过Spring+Mybatis整合,把一个用户的信息添加到数据库中.
实现步骤:
1.环境搭建
2.编写Dao和Service
3.书写配置类
4.测试
完整的项目结构如下:
1、环境搭建
1.1 导入jar包
这里我使用web项目
还有一个maven项目版的pom文件
<properties>
<org.springframework.version>4.2.4.RELEASE</org.springframework.version>
</properties>
<dependencies>
<!-- spring start -->
<!--spring core start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring core end-->
<!--spring aop start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spirng aop end-->
<!--spring aspects start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring aspects end-->
<!--spring instrumentation start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring instrumentation end-->
<!--spring messaging start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring messaging end-->
<!--spring data access start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring data access end-->
<!--spring web start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring web end -->
<!--spring test start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring test end -->
<!-- spring end -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
1.2、配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db1
jdbc.username=root
jdbc.password=1234
1.3、创建数据库和表
CREATE TABLE USER(
uid VARCHAR(32) PRIMARY KEY,
username VARCHAR(50),
PASSWORD VARCHAR(32)
)
2、编写dao和service
2.1、编写dao接口
public interface UserMapper extends Mapper {
}
2.2、编写service接口
public interface UserService {
public User findByPrimaryKey(String uid);
public void insertUser(User user);
}
2.3、Service实现类
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public User findByPrimaryKey(String uid) {
return userMapper.selectByPrimaryKey(uid);
}
@Override
public void insertUser(User user) {
userMapper.insert(user);
}
}
3、配置类
3.1、spring配置类
- 配置注解
1.1 扫描注解包
1.2加载properties文件
1.3 开启注解事务支持 - 获得properties数据(实现类、@Value)
- 配置数据源DataSource
- 配置事务管理器(DataSourceTransactionManager)
@Configuration
@ComponentScan(basePackages = {“com.czxy”})
@EnableTransactionManagement
@PropertySource(value = “classpath:db.properties”)
public class SpringConfig {
// 4.2.4版本 固定配置
@Bean
public static PropertySourcesPlaceholderConfigurer create(){
return new PropertySourcesPlaceholderConfigurer();
}
//读取数据库相关配置
@Value(" j d b c . d r i v e r " ) p r i v a t e S t r i n g d r i v e r C l a s s ; @ V a l u e ( " {jdbc.driver}") private String driverClass; @Value(" jdbc.driver")privateStringdriverClass;@Value("{jdbc.url}")
private String url;
@Value(" j d b c . u s e r n a m e " ) p r i v a t e S t r i n g u s e r n a m e ; @ V a l u e ( " {jdbc.username}") private String username; @Value(" jdbc.username")privateStringusername;@Value("{jdbc.password}")
private String password;
//数据源使用德鲁伊连接池
@Bean
public DataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driverClass);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
// 开启事务管理器
@Bean
@Resource
public DataSourceTransactionManager txManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
3.2、
- 配置session工厂,spring和MyBatis整合时,通过SqlSessionFactoryBean获得SqlSessionFactory
SqlSessionFactoryBean只能加载mapper映射文件
注解开发需要加载Mapper类,故需要对mapper进行扫描 - 配置映射扫描器
@Configuration
public class MyBatisConfig {
/**
* 构建SessionFactory对象,SessionFactory可以创建Session对象,最后使用Session操作数据库
* @param dataSource
* @return
* @throws Exception
/
@Bean
@Resource
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
// 1.通过工厂bean创建对象,最后需要调用 getObject()获得具体的对象
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
// 1.1 设置数据源
factoryBean.setDataSource(dataSource);
// 1.2 设置别名包扫描
factoryBean.setTypeAliasesPackage(“com.czxy.domain”);
// 1.3 全局配置:驼峰映射
org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
config.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(config);
// 2 插件配置
// 2.1 分页插件
PageHelper pageHelper = new PageHelper();
Properties pageProps = new Properties();
pageProps.setProperty(“dialect”, “mysql”);
pageProps.setProperty(“rowBoundsWithCount”, “true”);
pageHelper.setProperties(pageProps);
factoryBean.setPlugins(new Interceptor[] { pageHelper });
// 3 通过工厂bean获得 sqlSessionFactory
return factoryBean.getObject();
}
/*
* 扫描Dao的包,查找各种XxxMapper接口,创建好UserMapper等对象存入到IOC的容器中
* @return
*/
@Bean
public MapperScannerConfigurer mapperScanner() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage(“com.czxy.dao”);
return configurer;
}
}
4、测试类
4.1、方式1:整合Junit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class,MyBatisConfig.class})
public class TestA {
@Resource
private UserService userService;
@Test
public void test01(){
User user = new User(“u001”,“张三丰”,“123”);
userService.insertUser(user);
System.out.println(“添加完毕”);
}
}
测试结果: 成功添加用户信息
4.2、方式2:手动创建工厂
public class TestB {
public static void main(String[] args) {
//1.创建工厂,设置两个配置类
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class,MyBatisConfig.class);
//2.从工厂获取需要的对象
UserService userService = applicationContext.getBean(UserService.class);
//3.执行语句
User user = new User(“u800”,“zhangsan”,“123”);
userService.insertUser(user);
System.out.println(“添加完毕”);
}
}
以上是关于❤️Spring从入门到大神--Spring整合MyBatis的主要内容,如果未能解决你的问题,请参考以下文章
❤️Spring全家桶从入门到大神--spring mvc 参数绑定
❤️Spring全家桶从入门到大神--SpringMVC入门
❤️Spring全家桶从入门到大神-- spring mvc 拦截器