A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 曹老师 黑马粉丝团   /  2017-9-19 00:22  /  949 人查看  /  0 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

首先加入mybatis-spring-boot-stater的Maven依赖
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
配置数据源,这里使用的dbcp的数据源,具体大家可以看自己的情况来使用
src/main/resource中,添加一个prop.properties配置文件,这里面添加了一些数据库连接的信息
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1AE2.tmp.png
#jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.137.2:3306/weichat?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=2335
jdbc.maxIdel=120
jdbc.maxWait=100
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1AF3.tmp.png
然后加上下面的代码注入数据源
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B04.tmp.png
@Configuration
//这个注解导入刚才增加的jdbc配置文件
@PropertySource("classpath:prop.properties")
public class DataSourceConfiguration {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.maxActive}")
    private int maxActive;
    @Value("${jdbc.maxIdel}")
    private int maxIdel;
    @Value("${jdbc.maxWait}")
    private long maxWait;
   
    @Bean
    public BasicDataSource dataSource(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxIdle(maxIdel);
        dataSource.setMaxWait(maxWait);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(true);
        return dataSource;
    }
}
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B05.tmp.png
增加MyBatis的配置
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B15.tmp.png
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
/**
* @author zxj
*
*/
@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
    @Autowired
    private DataSource dataSource;
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
         return new DataSourceTransactionManager(dataSource);
    }
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        try {
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B16.tmp.png
然后需要配置MyBatis配置文件的路径,这个配置需要与上面的配置分开来写,因为它们有着一个先后顺序
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B17.tmp.png
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 扫描mybatis的接口
*
* @author zxj
*
*/
@Configuration
// 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //获取之前注入的beanName为sqlSessionFactory的对象
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        //指定xml配置文件的路径
        mapperScannerConfigurer.setBasePackage("com.framework.msg.mapper");
        return mapperScannerConfigurer;
    }
}
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B18.tmp.png
然后这就是配置完了,真的很简单,但是细心的朋友可能会问,代码里面怎么没有配置MyBatis接口的地址呢?
在这里,使用@Mapper注解来标识一个接口为MyBatis的接口,MyBatis会自动寻找这个接口,如下
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B19.tmp.png
import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface TestDao {
    @Select("select * from wx_userinfo;")
    public Map<String,Object> find();
   
    @Insert("insert into wx_userinfo(openid,status,nickname,sex,city,province,country,headimgurl,subscribe_time) "+
            "values(#{id},1,'nick',1,'city','provi','contr','img',now())")
    public int insert(@Param("id")int id);
}
file:///C:\Users\PC\AppData\Local\Temp\ksohtml\wps1B1A.tmp.png
这样就可以使用了,当然,在这之前,你得开启@ComponentScan注解,或者直接使用@SpringBootApplication(推荐)

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马