springboot整合mybatis

整合数据库

1.使用Jdbc连接数据库(了解)

1.加入poml文件

  <!-- jdbc连接数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.jdbc配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/edocdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root

3.使用JdbcTemplate操作(不适用)

 @Autowired
    private JdbcTemplate jdbcTemplate;
    
  @GetMapping("/edocInfo")  // 返回一个Map<String, Object>
    public Map<String, Object> queryEdocInfo(){
        List<Map<String,Object>> edocs = jdbcTemplate.queryForList("select * from edoc_entry");
        return edocs.get(0);
    }   

2.整合mabatis

1.加入poml文件

<!-- jdbc连接数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mybatis整和包 需要版本号 mybatis-spring-boot-starter-->
       <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>


2.使用注解方式编写sql语句

1.需要配置一个配置类()
@Configuration
@MapperScan("com.kgc.sbt.mapper")  // mapper扫描,给所有mapper创建实现类对象,不可省
public class MybatisConfig {
   /* @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        // 驼峰映射
        return  configuration -> configuration.setMapUnderscoreToCamelCase(true);
    }*/
}
@Mapper  // 给mapper创建实现类对象,如果有配置 @MapperScan("com.kgc.sbt.mapper") 可以省略
public interface EdocCategoryMapper {

    @Select("select * from edoc_category where id = #{id}")  //注解版
    EdocCategory queryCategoryById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id") // 自增主键值的返回
    @Insert("insert into edoc_category(name) values(#{name})")
    int queryInsertCategory(EdocCategoryForm edocCategoryForm);
}

3.使用配置文件来编写sql语句

1.在resoureces下创建mybatis目录 ,在创建一个mapper目录
2.创建全局配置mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        // 驼峰映射
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
3.创建mybatis-mapper.xml文件,编写sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kgc.sbt.mapper.DocEntryMapper">
    <select id="selectDocEntryById" resultType="com.kgc.sbt.domain.EdocEntrys">
        select id,c_id categoryId,title,summary,upload_user,create_date from edoc_entry where id = #{id}
    </select>
</mapper>
4.核心配置文件中配置mybatis配置
# mybatis自定义配置
mybatis:
  config-location: classpath:mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

4.使用ideal的datebase创建自动生成sql语句

1.生成代码
ideal的database点击+
选择mysql
name  -随便取(配置名)
Driver 选择 MySQL for 5.1 
host: 填写数据库ip和端口 localhost :3306
user ;用户名
password :密码
Database  库名
测试链接 apply ok 

出现表名 在表名上右击
选择mybatis generate
实体 model package : 选择实体生成的位置
接口 dao   package :选择接口生成的位置
xml配置 xml mapper  ;选择配置文件生成的位置 mybatis.mapper(这里用点)
默认勾选的5个 在选择 Use-Example  
如果要分页 加上 Page
2.使用语句
* Description: 使用mybatis插件 生成的代码来实现
 */
@RestController
public class EdocEntryController {
    @Autowired(required = false)
    private EdocEntryMapper edocEntryMapper;
    @GetMapping("/queryEdocEntryById")
    public EdocEntry queryEdocEntryById(@RequestParam Integer id){
        return edocEntryMapper.selectByPrimaryKey(Long.valueOf(id));
    }

    /**
    *@ClassName: EdocEntryController
    *@Description 多条件查询
    *@Author lzy
    *@Date 2021/5/29
    */
    @GetMapping("/queryEdocs")
    public List<EdocEntry> queryEdocsByExample(){
        // 动态拼接多个条件对象
        //创建条件对象
        EdocEntryExample edocEntryExample = new EdocEntryExample();
        // 是否去重
        edocEntryExample.setDistinct(false);
        // id倒叙
        edocEntryExample.setOrderByClause("id desc");
        // 创建多个条件,and多条件
        EdocEntryExample.Criteria criteria = edocEntryExample.createCriteria();
        criteria.andSummaryLike("%一%");
        criteria.andIdLessThan(5l);
        // 如果要使用or进行多条件连接
        EdocEntryExample.Criteria criteria1 = edocEntryExample.createCriteria();
        criteria.andUploadUserEqualTo("天蚕土豆");
        // 用or连接两个两个条件
        edocEntryExample.or(criteria1);
        // 分页查询
        edocEntryExample.setOffset(0l);
        edocEntryExample.setLimit(3);
        return  edocEntryMapper.selectByExample(edocEntryExample);
    }

3.如何使用读取sql文件

1.只需要在核心配置文件中修改

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/edocdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
     schema:
      - classpath:employees.sql  //指向sql文件
      
      然后直接启动就可以了

4.使用阿里巴巴Druid数据源(之前是tomcats)

此数据源可以进行后台监控

localhost:8088/druid

1.导入poml文件

<!-- 阿里巴巴druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

2.在核心配置文件中增加配置

# jdbc 配置
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/edocdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    # schema:
    # - classpath:employees.sql
    type: com.alibaba.druid.pool.DruidDataSource
    #数据源其他配置
    # 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
    initialSize: 5
    # 最小连接池数量
    minIdle: 5
    # 最大连接池数量
    maxActive: 20
    # 获取连接时最大等待时间,单位毫秒。
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    # 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
    validationQuery: SELECT 1 FROM DUAL
    # 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
    testWhileIdle: true
    # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnBorrow: false
    # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
    testOnReturn: false
    # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭
    poolPreparedStatements: false
    maxPoolPreparedStatementPerConnectionSize: 20
    # 合并多个DruidDataSource的监控数据
    useGlobalDataSourceStat: true
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计
    # 属性性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall
    filters: stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.Druid数据源配置

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix ="spring.datasource")
    public DataSource dataSource(){
        return  new DruidDataSource();
    }
    /**
     * 配置druid数据库的监控后台
     *
     * */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 初始化参数
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");
        // 是否允许访问
        initParams.put("allow", "");
        bean.setInitParameters(initParams);
        return bean;
    }
    /**
     * 配置web监控的过滤器
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        // 初始化参数
        Map<String, String> initParams = new HashMap<>();
        // 排除过滤,静态文件等
        initParams.put("exclusions", "*.css,*.js,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

5.springdate jpa使用

可以在自动创建实体对应的表

1.导入poml文件

<!--spring jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

2.实体类上加注解

@Data
@Entity
@Table(name = "edoc_user")  //表名
public class EdocUser {
    @Id  //主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自增
    private Integer id;
    
    @Column(name = "name",length = 32)
    private String name;
  
    @Column(name = "pwd",length = 32)
    private String password;
}

3.在核心配置文件中添加jpa

# jdbc 配置
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/edocdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    #jpa设置
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  

4.创建一个仓库包repository

创建一个接口 继承JpaRepository<EdocUser,Integer>  (对应的实体,主键类型)

5.在conttoller查询

* Description: springdate jpa
 */
@RestController
public class EodcUserController {
    @Autowired
    private EdocUserRepository edocUserRepository;


    @GetMapping("/edocUser")
    public EdocUser queryUserById(@RequestParam Integer id){

        return edocUserRepository.findOne(id);
    }

}




6.mybatisPlus的使用(单独解释的章节)

不要和mybatis混合使用

1.导入poml文件

   <!-- mybatis-plus 不能和mybatis混合使用-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.1.9</version>
        </dependency>

2.核心配置和mybatis一样的

3.创建实体,表名和实体名要一样

 * Description:  mybatisPlus Edoc_user实体名名称和表名一致
 */
@Data
public class Edoc_User {

    private Integer id;


    private String name;


    private String pwd;
}

4.在mapper创建接口

public interface DocUserMapper extends BaseMapper<Edoc_User> {
}

5.controller使用

@RestController
public class EodcUserController {

 
    @Autowired(required = false)
    private DocUserMapper docUserMapper;


    @GetMapping("/edocUsers")
    public List<Edoc_User> queryUsers(){

        return docUserMapper.selectList(null);
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值