在Spring Boot中配置Cassandra

x33g5p2x  于2022-10-06 转载在 Spring  
字(1.6k)|赞(0)|评价(0)|浏览(993)

Spring Boot 中使用 Cassandra 作为数据存储非常简单,因为我们已经准备好了一个starter POM。 让我们看看怎么做。

如果您正在开发一个简单的 Web 应用程序,那么您只需要两个依赖项。 从 CLI 执行:

$ spring init -dweb,data-cassandra -artifactId data-cassandra-demo

将添加以下依赖项:

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependencies>
        	 	
      <dependency>
          	    
         <groupId>org.springframework.boot</groupId>
          	    
         <artifactId>spring-boot-starter-data-cassandra</artifactId>
          	
      </dependency>
       	
      <dependency>
          		
         <groupId>org.springframework.boot</groupId>
          		
         <artifactId>spring-boot-starter-web</artifactId>
          	
      </dependency>
        	
      <dependency>
          		
         <groupId>org.springframework.boot</groupId>
          		
         <artifactId>spring-boot-starter-test</artifactId>
          		
         <scope>test</scope>
          	
      </dependency>
       
   </dependencies>
    
</project>

在我们开始编码之前,重要的是我们通过 spring.data.cassandra 为连接信息提供端口、键空间名称和接触点属性:

spring.data.cassandra.keyspace-name=mykeyspace spring.data.cassandra.contact-points=acme.com spring.data.cassandra.port=9042

为了创建您的映射模型,请使用@org.springframework.data.cassandra.mapping.Table 和@org.springframework.data.cassandra.mapping.PrimaryKey,如下例所示:

import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
@Table
public class Customer {
  @PrimaryKey private int id;
  private String name;
}

在此示例中,@Table 标识要作为表持久保存到 Cassandra 的域对象,@PrimaryKey 标识实体的主键字段。

然后,您可以使用 @Query 对象创建您的 Repository 对象以从 Cassandra 检索数据:

public interface CustomerRepository extends CrudRepository<Customer, String> {
  @Query(value = "SELECT * FROM customer WHERE name=?0")
  public List<Customer> findByName(String name);
}

相关文章

微信公众号

最新文章

更多