SpringBoot集成Mybatis

SpringBoot与SpringFrameWork最大的区别是约定优于配置,今天尝试下如何使用注解而不是基于XML配置来使用Mybatis

【SpringBoot集成Mybatis】

1.pom依赖配置

<!-- 导入Mysql数据库链接jar包 -->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.41</version>
 </dependency>     


2.dataSource设置,springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3308/xxx?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = xxx
spring.datasource.password = xxx

3.定义业务模型和Mybatis的dao接口(mapper),Mapper注解是关键

package com.app.base;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper
{
    //CREATE TABLE IF NOT EXISTS `user_tbl`(`id` INT UNSIGNED ,`properity` VARCHAR(400)         
    //NOT NULL,`val` VARCHAR(400) NOT NULL,PRIMARY KEY(`id`) ) ENGINE=InnoDB DEFAULT 
    //CHARSET=utf8;
    @Select("select * from user_tbl")
    public List<User> select(User parm);
}
package com.app.base;

import lombok.Getter;
import lombok.Setter;

public class User
{
    @Getter
    @Setter
    private int id;
    
    @Getter
    @Setter
    private String properity;
    
    @Getter
    @Setter
    private String val;
}

4.SpringBoot启动项中设置扫描自定义mapper和加载datasource的 properties配置
@MapperScan("com.app.base") 

@Configuration
@ComponentScan(basePackages={"com.app"})
@MapperScan("com.app.base")
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix="jdbc")
public class App 
{   
    
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);     
    }
}

5.数据库操作层Dao,

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
@Service
public class Dao
{
    
    @Autowired
    private UserMapper mapPer;
    
    @PostConstruct
    private void init()
    {        
        List<User> results = mapPer.select(null);    
        System.out.print(results.get(0).getProperity());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值