SpringBoot基础:使用MyBatis访问MySQL

337 阅读3分钟

参考博客链接:blog.csdn.net/qq_40511966…

步骤一:引入MyBatis依赖:

      <!-- mybatis --> 

        <dependency> 

            <groupId>org.mybatis.spring.boot</groupId> 

            <artifactId>mybatis-spring-boot-starter</artifactId> 

            <version>2.0.1</version> 

        </dependency> 

      <!-- 项目启动时,对数据库表进行操作 --> 

        <dependency> 

            <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> 

            <artifactId>mybatis-enhance-actable</artifactId> 

            <version>1.4.1.RELEASE</version> 

        </dependency> 



        <dependency> 

            <groupId>com.alibaba</groupId> 

            <artifactId>druid</artifactId> 

            <version>1.1.18</version> 

        </dependency> 

步骤二:配置application.properties文件:

server.port=9707 



spring.datasource.url = jdbc:mysql://localhost:3306/MyBatis?characterEncoding=utf8&useSSL=false&autoReconnect=true 

spring.datasource.username=root 

spring.datasource.password=123456 

spring.datasource.driver-class-name=com.mysql.jdbc.Driver 



#create,系统启动后,会将所有表删除,然后根据路径包中的实体类进行重新建表(会破坏原有数据) 

#none,不做任何处理 

#系统启动是会自动判断哪些表需要新建,哪些字段需要修改(不会破坏原有数据) 

mybatis.table.auto=update 

#用来配置要扫描的用于创建表的对象的包名 

mybatis.model.pack=com.example.MyBatis.daomain 

#用来区别数据库,预计会支持这四种数据库mysql/oracle/sqlserver/postgresql,但目前仅支持mysql 

mybatis.database.type=mysql 

步骤三:配置MyBatis,借助实体类自动创建数据库表

1、配置启动类:

import org.mybatis.spring.mapper.MapperScannerConfigurer; 

import org.springframework.boot.autoconfigure.AutoConfigureAfter; 

import org.springframework.context.annotation.Bean; 

import org.springframework.context.annotation.Configuration; 

/** 

* 

* @ClassName: MyBatisMapperScannerConfig 

* @Description: 

* @Author :chengwenixng 

* @Copyright: Smartlab411 

* @DateTime 2021-05-06 20:00:47 

*/ 

//相当于<beans></beans>标签。表明本类自动生成Bean 

@Configuration 

//当DataSourceAutoConfiguration这个类加载完成后再加载本类 

@AutoConfigureAfter(MybatisTableConfig.class) 

public class MyBatisMapperScannerConfig { 

     @Bean 

        public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{ 

            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); 

            //MapperScannerConfigurer 在使用时只需通过 basePackage 属性指定需要扫描的包即可, Spring 会自动的通过包中的接口来生成映射器() 

            mapperScannerConfigurer.setBasePackage("com.example.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*"); 

            /** 

             * sqlSessionFactory的注入方式有四种,分别是sqlSessionFactory,sqlSessionFactoryBeanName,sqlSessionTemplate,sqlSessionTemplateBeanName,而sqlSessionFactory这种已经过时,所以我们用到的是sqlSessionFactoryBeanName 

             * 原因1:注入sqlSessionFactory,(可以不用配置)只有当配置多数据源的时候,这时会有多个sqlSessionFactory,可以通过改属性来指定哪一个sqlSessionFactory 

             * 原因2:注入sqlSessionFactory,后面的value是SqlSessionFactory的bean的名字,也就是sqlSessionFactory的id当我们的mapperscannerconfigurer启动的时候,可能会出现我们的jdbc.properties文件未被加载,这样的话它拿到的DataSource就是错误的,因为像${jdbc.url}这类的属性还没有被替换掉,所以通过BeanName后处理的方式,当我们去用我们的Mybatis的时候,它才会去找我们对应的sqlSessionFactory,为了防止它提前初始化我们的sqlSessionFactory . 

             */ 

            // 由Spring框架自注入sqlSessionFactoryBeanName 

            mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); 

            return mapperScannerConfigurer; 

        } 

} 

2、springboot下配置druid

package com.example.MyBatis.config; 



import com.alibaba.druid.pool.DruidDataSource; 



import org.mybatis.spring.SqlSessionFactoryBean; 

import org.slf4j.Logger; 

import org.slf4j.LoggerFactory; 

import org.springframework.beans.factory.annotation.Value; 

import org.springframework.context.annotation.Bean; 

import org.springframework.context.annotation.ComponentScan; 

import org.springframework.context.annotation.Configuration; 

import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 

import org.springframework.jdbc.datasource.DataSourceTransactionManager; 



/** 

* 添加DruidConfiguration配置类 

* @ClassName: MybatisTableConfig 

* @Description: 

* @Author :chengwenixng 

* @Copyright: Smartlab411 

* @DateTime 2021-05-06 20:01:26 

*/ 



@Configuration 

@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"}) 

public class MybatisTableConfig { 



    private static final Logger log = LoggerFactory.getLogger(MybatisTableConfig.class); 



    @Value("${spring.datasource.driver-class-name}") 

    private String driver; 

    

    /** 

     * 数据库url 

     */ 

    @Value("${spring.datasource.url}") 

    private String url; 

    

    /** 

     * 数据库用户名 

     */ 

    @Value("${spring.datasource.username}") 

    private String username; 



    /** 

     *数据库密码 

     */ 

    @Value("${spring.datasource.password}") 

    private String password; 



    @Bean 

    public DruidDataSource dataSource() { 

        DruidDataSource dataSource = new DruidDataSource(); 

        //driverClassName:数据库驱动类的名称。 

        dataSource.setDriverClassName(driver); 

      //driverClassName:数据库路径 

        dataSource.setUrl(url); 

        dataSource.setUsername(username); 

        dataSource.setPassword(password); 

        dataSource.setMaxActive(30); 

        dataSource.setInitialSize(10); 

        dataSource.setValidationQuery("SELECT 1"); 

        dataSource.setTestOnBorrow(true); 

        return dataSource; 

    } 

    /** 

     * 事务管理 

     * @Title: dataSourceTransactionManager 

     * @Description: 

     * @Author coding 

     * @DateTime 2021-05-07 10:58:25 

     * @return 

     */ 

    @Bean 

    public DataSourceTransactionManager dataSourceTransactionManager() { 

        //此事务管理器是针对传统的JDBC进行事务管理 

        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); 

        dataSourceTransactionManager.setDataSource(dataSource()); 

        return dataSourceTransactionManager; 

    } 

    /** 

     * SqlSessionFactoryBean有能力监控 Application发出的一些事件通知 

     * @Title: sqlSessionFactory 

     * @Description: 

     * @Author coding 

     * @DateTime 2021-05-07 11:01:14 

     * @return 

     * @throws Exception 

     */ 

    @Bean 

    public SqlSessionFactoryBean sqlSessionFactory() throws Exception{ 

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 

        sqlSessionFactoryBean.setDataSource(dataSource()); 

        /** 

         * PathMatchingResourcePatternResolver的作用: 根据路径的开头,返回不同的Resource 

         */ 

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml")); 

        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.MyBatis.daomain.*"); 

        return sqlSessionFactoryBean; 

    } 



} 

3、实体类:

package com.example.MyBatis.daomain; 





import java.util.Date; 





import com.gitee.sunchenbin.mybatis.actable.annotation.Column; 

import com.gitee.sunchenbin.mybatis.actable.annotation.Table; 

import com.gitee.sunchenbin.mybatis.actable.command.BaseModel; 

import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; 





@Table(name = "user_entity") 

public class UserEntity extends BaseModel{ 

    

    private static final long serialVersionUID = 1L; 

    

    /** 

     * 数据库自增长ID 

     */ 

    @Column(name = "id",type = MySqlTypeConstant.INT,length = 11,isKey = true,isAutoIncrement = true) 

    private Long id; 

    /** 

     * 用户名称 

     */ 

    @Column(name = "name",type = MySqlTypeConstant.VARCHAR, length = 45) 

    private String name; 

    /** 

     * 用户年龄 

     */ 

    @Column(name = "age",type = MySqlTypeConstant.BIGINT,length = 5) 

    private Integer age; 

    /** 

     * 创建时间 

     */ 

    @Column(name = "create_time",type = MySqlTypeConstant.DATETIME) 

    private Date createTime = new Date(); 

    public Long getId() { 

        return id; 

    } 

    public void setId(Long id) { 

        this.id = id; 

    } 

    public String getName() { 

        return name; 

    } 

    public void setName(String name) { 

        this.name = name; 

    } 

    public Integer getAge() { 

        return age; 

    } 

    public void setAge(Integer age) { 

        this.age = age; 

    } 

    public Date getCreateTime() { 

        return createTime; 

    } 

    public void setCreateTime(Date createTime) { 

        this.createTime = createTime; 

    } 

} 

4、UserEntityMapper接口:

package com.example.MyBatis.mapper; 





import java.util.List; 





import org.apache.ibatis.annotations.Insert; 

import org.apache.ibatis.annotations.Mapper; 

import org.apache.ibatis.annotations.Param; 

import org.apache.ibatis.annotations.Select; 





import com.example.MyBatis.daomain.UserEntity; 





/** 

* 

* @ClassName: UserMapper 

* @Description: 

* @Author :chengwenixng 

* @Copyright: Smartlab411 

* @DateTime 2021-05-06 20:26:51 

*/ 

@Mapper 

public interface UserEntityMapper{ 

   @Select("SELECT * FROM user_entity WHERE NAME = #{name}") 

    UserEntity findByName(@Param("name") String name); 

    

    @Insert("INSERT INTO user_entity(NAME, AGE) VALUES(#{name}, #{age})") 

    int insert(@Param("name") String name, @Param("age") Integer age); 



    @Select("SELECT * FROM user_entity") 

    List<UserEntity> findAll(); 



} 

最后在数据库中创建相应的数据库后运行项目,发现数据库中自动生成了用户表单;

注意:该笔记中部分代码和插件接口还需要深入了解;

疑问:application.properties文件中已经对数据库连接的相关了配置,为什么还要创建MybatisTableConfig 类配置druid高性能的实时分析型数据库