SpringBoot: 通过MyBatis访问ClickHouse

本文介绍了如何在SpringBoot项目中集成ClickHouse数据库,包括添加相关依赖、配置数据源、创建实体类映射数据表、定义mapper以及在controller中调用操作。
摘要由CSDN通过智能技术生成

一、ClickHouse中建表,添加数据
在这里插入图片描述
在这里插入图片描述
二、SpringBoot项目添加mybatis、clickhouse、druid相关依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>ru.yandex.clickhouse</groupId>
            <artifactId>clickhouse-jdbc</artifactId>
            <version>0.3.2</version>
        </dependency>

三、配置文件进行配置数据源(application.yml):


spring:
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    clickhouse:
      driverClassName: ru.yandex.clickhouse.ClickHouseDriver
      url: jdbc:clickhouse://xxx.xxx.xxx.xxx:8123/helloworld #clickhouse地址
      userName: default
      password: default
      initialSize: 10
      maxActive: 100
      minIdle: 10
      maxWait: 6000
      validationQuery: SELECT 1
server:
  port: 9234



四、创建实体类映射数据表:

package cn.edu.tju.domain;

public class MyFirstTable {
    private int price;
    private String addr;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "MyFirstTable{" +
                "price=" + price +
                ", addr='" + addr + '\'' +
                '}';
    }
}

五、定义mapper

package cn.edu.tju.mapper;

import cn.edu.tju.domain.MyFirstTable;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface MyMapper {
    @Select("select count(1) from my_first_table")
    int getCount();

    @Select("select * from my_first_table where price =#{price}")
    MyFirstTable getByPrice(int price);

}

六、配置SqlSessionFactory

package cn.edu.tju.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.datasource.clickhouse")
public class ClickHouseConfig {
    private String username;
    private String password;
    private String driverClassName ;
    private String url ;
    private Integer initialSize ;
    private Integer maxActive ;
    private Integer minIdle ;
    private Integer maxWait ;
    private String validationQuery;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }
}


package cn.edu.tju.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.sql.DataSource;


@Configuration
public class DruidConfig {

    @Autowired
    private ClickHouseConfig clickHouseConfig;

    @Bean(name = "clickHouseDataSource")
    public DataSource dataSource() throws ClassNotFoundException {
        Class clazz = Class.forName("com.alibaba.druid.pool.DruidDataSource");
        DruidDataSource dataSource = (DruidDataSource) DataSourceBuilder
                .create()
                .driverClassName(clickHouseConfig.getDriverClassName())
                .type(clazz)
                .url(clickHouseConfig.getUrl())
                .username(clickHouseConfig.getUsername())
                //.password(clickHouseConfig.getPassword())
                .build();
        dataSource.setMaxWait(clickHouseConfig.getMaxWait());
        dataSource.setValidationQuery(clickHouseConfig.getValidationQuery());
        return dataSource;
    }

    @Bean("sqlSessionFactory")
    public SqlSessionFactory clickHouseSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource());
        factory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return factory.getObject();
    }
}


七、controller中注入mapper(此处省略了service)

package cn.edu.tju.controller;

import cn.edu.tju.domain.MyFirstTable;
import cn.edu.tju.mapper.MyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    @Autowired
    private MyMapper myMapper;

    @RequestMapping("/hello")
    public String getInfo(){
        int result = myMapper.getCount();
        System.out.println(result);
        return "hello";
    }

    @RequestMapping("/hello2")
    public String getInfo2(){
        MyFirstTable myFirstTable = myMapper.getByPrice(2015);
        System.out.println(myFirstTable);

        return "hello2";
    }
}

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Spring Boot 3.2.4版本集成Batis 2.1.3时,出现"Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"错误的原因是没有正确配置MyBatis的相关属性。 解决这个问题的方法是在Spring Boot的配置文件中添加正确的MyBatis配置。具体步骤如下: 1. 确保已经在pom.xml文件中添加了MyBatisMyBatis-Spring的依赖。 2. 在Spring Boot的配置文件(通常是application.properties或application.yml)中添加以下配置: - 如果使用sqlSessionFactory: ```properties mybatis.config-location=classpath:mybatis-config.xml mybatis.mapper-locations=classpath:mapper/*.xml ``` - 如果使用sqlSessionTemplate: ```properties mybatis.mapper-locations=classpath:mapper/*.xml ``` 这些配置指定了MyBatis的配置文件位置和Mapper文件的位置。 3. 创建一个MyBatis的配置文件(mybatis-config.xml),并在其中配置sqlSessionFactory或sqlSessionTemplate。示例配置如下: - 使用sqlSessionFactory: ```xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <!-- 配置实体类别名 --> <package name="com.example.entity"/> </typeAliases> <mappers> <!-- 配置Mapper接口 --> <mapper resource="mapper/ExampleMapper.xml"/> </mappers> </configuration> ``` - 使用sqlSessionTemplate: ```xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <!-- 配置实体类别名 --> <package name="com.example.entity"/> </typeAliases> </configuration> ``` 这些配置文件中的内容根据你的具体项目需求进行修改。 4. 确保Mapper接口和对应的Mapper XML文件已经正确创建,并且位于指定的位置。 完成以上步骤后,重新运行项目,应该就能够解决"Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值