【发布时间】:2020-11-18 23:49:32
【问题描述】:
我是 Cassandra 的新手,这是第一次,以前从未使用过,到目前为止我们一直使用 Spring Boot 和 MySql 作为我们的数据库,但现在我们计划将我们的数据库迁移到 Cassandra,最低限度代码或没有变化。 这是我们一直在使用的代码示例演示。
配置类
package com.example.demo.config;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Generated;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.HashMap;
import static org.hibernate.cfg.AvailableSettings.*;
@Configuration
@EnableTransactionManagement
@EnableJpaAuditing
@EnableJpaRepositories(entityManagerFactoryRef = "orclEntityManagerFactory", transactionManagerRef = "orclTransactionManager", basePackages = {"com.example.demo.repository"})
@Generated
public class DataSourceConfig {
@Value("${spring.datasource.driver-class-name}")
private String orclDbDriver;
@Value("${spring.datasource.url}")
private String orclDbConnUrl;
@Value("${spring.datasource.username}")
private String orclDbUsername;
@Value("${spring.datasource.password}")
private String orclDbPassword;
@Value("${spring.datasource.poolName}")
private String dataSourcePoolName;
@Value("${spring.jpa.properties.hibernate.dialect}")
private String orclHibernateDialect;
@Value("${spring.jpa.hibernate.ddl-auto}")
private String hibernateDDL;
@Value("${spring.jpa.show-sql}")
private boolean showSql;
@Value("${spring.datasource.packagesToScan}")
private String[] packagesToScan;
public DataSourceConfig() {
}
@Bean
@Primary
public DataSource orclDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(this.orclDbDriver);
dataSource.setJdbcUrl(this.orclDbConnUrl);
dataSource.setUsername(this.orclDbUsername);
dataSource.setPassword(this.orclDbPassword);
dataSource.setPoolName(this.dataSourcePoolName);
return dataSource;
}
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean orclEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(this.orclDataSource());
factory.setPackagesToScan(this.packagesToScan);
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setGenerateDdl(Boolean.TRUE);
jpaVendorAdapter.setShowSql(showSql);
jpaVendorAdapter.setDatabasePlatform(orclHibernateDialect);
factory.setJpaVendorAdapter(jpaVendorAdapter);
HashMap<String, Object> properties = new HashMap();
properties.put(HBM2DDL_AUTO, this.hibernateDDL);
properties.put(DIALECT, this.orclHibernateDialect);
properties.put(STATEMENT_BATCH_SIZE, "500");
properties.put(ORDER_UPDATES, "true");
properties.put(ORDER_INSERTS, "true");
properties.put(GENERATE_STATISTICS, "true");
factory.setJpaPropertyMap(properties);
return factory;
}
@Bean
@Primary
public JpaTransactionManager orclTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(this.orclEntityManagerFactory().getObject());
return transactionManager;
}
}
控制器类
import com.example.demo.entity.Child;
import com.example.demo.repository.ChildRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Timestamp;
import java.util.List;
@RestController
public class HelloController {
@Autowired
private ChildRepository childRepository;
@GetMapping("put")
public Child getHello() {
Child child = new Child();
child.setName("shrikant");
child.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
return childRepository.save(child);
}
@GetMapping("get")
public List<Child> hello() {
return childRepository.findAll();
}
}
存储库
package com.example.demo.repository;
import com.example.demo.entity.Child;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ChildRepository extends JpaRepository<Child, Long> {
}
应用程序.dev
spring.datasource.url=jdbc:mysql://localhost:3306/student_db?jdbcCompliantTruncation=false&sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&useSSL=false&useServerPrepStmts=false&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.poolName=springHikariCp
spring.jpa.generate-ddl=true
spring.jpa.database.schema=student_db
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.datasource.packagesToScan=com.example.demo.entity
spring.profiles.active=dev
build.gradle
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
compile 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
我在 google 的帮助下安装了 Cassandra,并且能够使用 cqlsh 登录。
创建的键空间
CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};
在 Gradle 中添加 Cassandra 依赖项
compile 'org.springframework.boot:spring-boot-starter-data-cassandra'
但是 application.properties 中的配置属性应该是什么,我在 Google 上找不到任何创建自定义数据源的示例,都使用 Spring Boot 自动配置,但我不能这样做,因为这将是一个重大的代码更改。
【问题讨论】:
-
除非您在关系数据库中的数据模型是专门为 nosql 数据库设计的,否则您将无法在没有实际代码更改的情况下进行移植。我认为需要首先查看数据模型,因为如果以正常的关系方式设计,您已经可以确定这不会是“最小”的变化。
-
补充 Andrew 的观点 - Cassandra 中的所有内容都从查询开始 - 所有表都按照您获取数据的方式进行组织...
-
Spring Data Cassandra 非常适合小型项目。但是,如果您希望这在某个时候能够扩展,Spring Data Cassandra 在幕后使用了一些反模式。我总是建议人们使用 DataStax Java 驱动程序:docs.datastax.com/en/developer/java-driver/4.8
标签: mysql spring-boot cassandra