mybatis与spring3.1整合

因spring3发布时mybatis还没有出正式版本,所以spring没有整合最新的mybatis.不过社区倒是开发了一个中间件。

 

需要的jar包

mybatis-3.0.6.jar

mybatis-spring-1.0.2.jar

 

要点:

1.在spring中配置mybatis工厂类

2.在dao层使用spring注入的的工具bean对数据进行操作

整合时,可以有四种方式来使用mybatis进行数据处理。

 

spring 中必须的配置。

spring的配置文件中加入以下内容

 

Xml代码   收藏代码
  1. <!-- MyBatis配置 -->  
  2.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  3.         <property name="dataSource" ref="c3p0DataSource" />  
  4.         <property name="configLocation" value="/WEB-INF/config/db/MyBatisConfiguration.xml" />  
  5.         <property name="mapperLocations" value="/WEB-INF/config/db/*Mapper.xml" />  
  6.         <property name="typeAliasesPackage" value="${mybatis.alias.basepackage}" />  
  7.     </bean>  

 

1.SqlSessionFactoryBean (必需)

   就是中间件所需的处理类

 

2.dataSource  (必需)

   spring中数据源引用

 

3.configLocation  (可选)

   Mybatis自身的配置文件,一般用来声明别名

 

4.mapperLocation  (可选)

   mybatis的映射文件

 

5.typeAliasesPackage (可选)

   要映射类的包路径,如果使用了这种方式,则configLocation中不必再进行声明

 

 

 

使用mybatis进行数据处理的四种方式(SqlSessionTemplate/SqlSessionDaoSupport/MapperFactoryBean/MapperScannerConfigurer)

不同方式的特点

  1. SqlSessionTemplate  这个需要写配置文件,在实现类中注入sqlsession,再使用sqlsession,是细颗粒控制
  2. SqlSessionDaoSupport   这个只需要在实现类中继承特殊类就可以使用sqlsession
  3. MapperFactoryBean  这个要写配置文件,把对应的所有接口在配置文件中引用即可,无需写实现类
  4. MapperScannerConfigurer  这个要写配置文件,只要给出接口所在的包即可,会自动把包中的接口引入,无需写实现类
  • SqlSessionTemplate
  1. 配置文件加入新配
    Java代码   收藏代码
    1. <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
    2.   <constructor-arg index="0" ref="sqlSessionFactory" />  
    3.   <constructor-arg index="1" value="BATCH" /><!--- 如果想要进行批量操作可加入这个属性 ->  
    4. </bean>  
     
  2. 注入sqlsession()
    Java代码   收藏代码
    1. @Reasource //使用spring3的注解注入  
    2. private SqlSession sqlSession;  
     
  3. 使用sqlsession来进行操作
    Java代码   收藏代码
    1. public User getUser(String userId) {  
    2.     return (User) sqlSession.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);  
    3.   }  
  • SqlSessionDaoSupport(sqlSessionFactory会被spring自动装配,不需要手动注入)
  1. 继承SqlSessionDaoSupport类
    Java代码   收藏代码
    1. public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {  
    2.   
    3. }  
     
  2. 使用getSqlSession()方法取sqlSession来进行数据处理
    Java代码   收藏代码
    1. public User getUser(String userId) {  
    2.     return (User) getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);  
    3.   }  
     
  • MapperFactoryBean
  1. 写配置文件,引入每个DAO接口
    Xml代码   收藏代码
    1. <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    2.   <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />  
    3.   <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
    4. </bean>  
     
  2. 在业务层可直接注入dao的接口进行操作
  • MapperScannerConfigurer
  1. 写配置文件,配置包名将自动引入包中的所有接口
    Xml代码   收藏代码
    1. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
    2.   <property name="basePackage" value="org.mybatis.spring.sample.mapper" />  
    3. </bean>  
     
  2. 在业务层可直接注入DAO接口操作,注入时使用的是接口名,其首字母小写
  3. 注意:如果有别的实现类,其提供的名称如果是接口名,且首字母小写,则会在启动时出现冲突错误
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个非常流行的 Java Web 框架,而 MyBatis-Plus 是一个优秀的 ORM 框架,它可以帮助我们更加方便地操作数据库。本篇文章将介绍如何在 Spring Boot 中整合 MyBatis-Plus 3.1。 ## 1. 准备工作 在开始整合之前,我们需要准备好以下环境: - JDK 8+ - Maven 3.2+ - IDE(例如 IntelliJ IDEA 或 Eclipse) ## 2. 创建 Spring Boot 项目 首先,我们需要创建一个 Spring Boot 项目。可以使用 Spring Initializr 来快速创建一个项目。在创建项目的过程中,我们需要选择以下的依赖: - Spring Web - MyBatis-Plus 如果你使用的是 IntelliJ IDEA,可以使用以下方式创建项目: 1. 打开 IntelliJ IDEA,选择 "Create New Project"。 2. 在弹出的对话框中选择 "Spring Initializr"。 3. 配置项目的基本信息,例如 Group、Artifact、Name 等。 4. 在 "Dependencies" 中选择 "Spring Web" 和 "MyBatis-Plus"。 5. 点击 "Next",确认配置信息。 6. 点击 "Finish",完成项目的创建。 如果你使用的是 Eclipse,可以参考以下的步骤: 1. 打开 Eclipse,选择 "File" -> "New" -> "Other"。 2. 在弹出的对话框中选择 "Spring Starter Project"。 3. 配置项目的基本信息,例如 Group、Artifact、Name 等。 4. 在 "Dependencies" 中选择 "Spring Web" 和 "MyBatis-Plus"。 5. 点击 "Finish",完成项目的创建。 ## 3. 配置 MyBatis-Plus 完成项目的创建后,我们需要进行一些配置,以便让 Spring Boot 和 MyBatis-Plus 正常工作。 ### 3.1 配置数据源 首先,我们需要配置数据源。在 Spring Boot 中,我们可以使用以下方式配置数据源: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 这里我们使用的是 MySQL 数据库,你可以根据自己的实际情况进行修改。 2. 在启动类中添加 @EnableTransactionManagement 注解,开启事务管理: ```java @SpringBootApplication @EnableTransactionManagement public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.2 配置 MyBatis-Plus 接下来,我们需要配置 MyBatis-Plus。在 Spring Boot 中,我们可以使用以下方式配置 MyBatis-Plus: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml mybatis-plus: mapper-locations: classpath*:mapper/*.xml type-aliases-package: com.example.demo.entity ``` 这里的 mapper-locations 表示 Mapper 文件的位置,type-aliases-package 表示实体类的包路径。 2. 在启动类中添加 @MapperScan 注解,指定 Mapper 文件的包路径: ```java @SpringBootApplication @EnableTransactionManagement @MapperScan("com.example.demo.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.3 配置分页插件 MyBatis-Plus 内置了一个分页插件,可以帮助我们更加方便地进行分页查询。 在 Spring Boot 中,我们可以使用以下方式配置分页插件: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml mybatis-plus: configuration: # 分页插件 page-helper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql ``` 这里的 helper-dialect 表示数据库类型,reasonable 表示是否启用合理化查询,support-methods-arguments 表示支持多参数查询,params 表示传递给 Mapper 的参数名。 2. 在 Mapper 接口中添加 Page 参数,如下所示: ```java public interface UserMapper extends BaseMapper<User> { List<User> selectUserList(Page<User> page); } ``` ### 3.4 配置自动填充插件 MyBatis-Plus 还内置了一个自动填充插件,可以帮助我们更加方便地进行数据填充。 在 Spring Boot 中,我们可以使用以下方式配置自动填充插件: 1. 在实体类中添加 @TableField 注解,并指定填充策略: ```java @Data public class User { private Long id; private String name; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; } ``` 这里的 fill 表示填充策略,INSERT 表示插入时填充,UPDATE 表示更新时填充。 2. 在 Mapper 接口中添加 @Insert 注解,并指定插入方式: ```java public interface UserMapper extends BaseMapper<User> { @Insert("insert into user(name,create_time,update_time) values(#{name},#{createTime},#{updateTime})") int insertUser(User user); } ``` 这里的 @Insert 注解表示插入数据,#{} 中的属性名与实体类中的属性名一致。 ## 4. 使用 MyBatis-Plus 完成配置后,我们就可以使用 MyBatis-Plus 进行数据库操作了。下面我们来看一些使用示例。 ### 4.1 基本操作 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User selectById(Long id) { return userMapper.selectById(id); } public List<User> selectList() { return userMapper.selectList(null); } public int insert(User user) { return userMapper.insert(user); } public int updateById(User user) { return userMapper.updateById(user); } public int deleteById(Long id) { return userMapper.deleteById(id); } } ``` 这里的 selectById、selectList、insert、updateById、deleteById 分别表示根据 id 查询、查询列表、插入、更新和删除。 ### 4.2 分页查询 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> selectUserList(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return userMapper.selectUserList(page); } } ``` 这里的 selectUserList 表示分页查询,pageNum 表示页码,pageSize 表示每页大小。Page<User> 表示分页对象。 ### 4.3 自动填充 ```java @RestController public class UserController { @Autowired private UserService userService; @PostMapping("/user") public int insert(User user) { return userService.insert(user); } } ``` 这里的 insert 表示插入数据,当插入数据时,createTime 和 updateTime 会自动填充。 ## 5. 总结 本篇文章介绍了如何在 Spring Boot 中整合 MyBatis-Plus 3.1。首先,我们需要创建一个 Spring Boot 项目,并添加相应的依赖。然后,我们需要进行一些配置,包括数据源、MyBatis-Plus、分页插件和自动填充插件。最后,我们使用 MyBatis-Plus 进行数据库操作。 MyBatis-Plus 是一个非常优秀的 ORM 框架,它可以帮助我们更加方便地操作数据库。如果你想提高自己的开发效率,不妨尝试一下 MyBatis-Plus。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值