cassandra入门(二):自定义类型使用和ORM

简介:

直接贴代码,cql和代码有些地方与分享电子书里的javaDriver21.pdf有些出入,请以博文为准,cql和代码都是实测跑通的。

cql脚本(在cqlsh.bat窗口里跑):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

CREATE KEYSPACE complex

WITH replication = {'class' : 'SimpleStrategy', 'replication_factor' :

3};

CREATE TYPE complex.phone (

alias text,

number text

);

CREATE TYPE complex.address (

street text,

city text,

zip_code int,

phones list<frozen<phone>>

);

CREATE TABLE complex.accounts (

email text PRIMARY KEY,

name text,

addr frozen<address>

);

自定义类型:phone和address。
表:accounts 。

maven依赖:

1

2

3

4

5

6

7

8

9

10

<dependency>

<groupId>com.datastax.cassandra</groupId>

<artifactId>cassandra-driver-core</artifactId>

<version>2.1.5</version>

</dependency>

<dependency>

<groupId>com.datastax.cassandra</groupId>

<artifactId>cassandra-driver-mapping</artifactId>

<version>2.1.5</version>

</dependency>

Phone类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

import com.datastax.driver.mapping.annotations.UDT;

@UDT(keyspace = "complex", name = "phone")

public class Phone {

private String alias;

private String number;

public Phone() {

}

public Phone(String alias, String number) {

this.alias = alias;

this.number = number;

}

public String getAlias() {

return alias;

}

public void setAlias(String alias) {

this.alias = alias;

}

public String getNumber() {

return number;

}

public void setNumber(String number) {

this.number = number;

}

}

Address类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

import java.util.List;

import com.datastax.driver.mapping.annotations.Field;

import com.datastax.driver.mapping.annotations.Frozen;

import com.datastax.driver.mapping.annotations.UDT;

@UDT(keyspace = "complex", name = "address")

public class Address {

private String street;

private String city;

@Field(name = "zip_code")

private int zipCode;

@Frozen("list<frozen<phone>>")

private List<Phone> phones;

public Address() {

}

public Address(String street, String city, int zipCode, List<Phone> phones) {

this.street = street;

this.city = city;

this.zipCode = zipCode;

this.phones = phones;

}

public String getStreet() {

return street;

}

public void setStreet(String street) {

this.street = street;

}

public String getCity() {

return city;

}

public void setCity(String city) {

this.city = city;

}

public int getZipCode() {

return zipCode;

}

public void setZipCode(int zipCode) {

this.zipCode = zipCode;

}

public List<Phone> getPhones() {

return phones;

}

public void setPhones(List<Phone> phones) {

this.phones = phones;

}

}

Account类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

import com.datastax.driver.mapping.annotations.Column;

import com.datastax.driver.mapping.annotations.Frozen;

import com.datastax.driver.mapping.annotations.PartitionKey;

import com.datastax.driver.mapping.annotations.Table;

import com.google.common.base.Objects;

@Table(keyspace = "complex", name = "accounts")

public class Account {

@PartitionKey

private String email;

private String name;

@Column(name = "addr")

@Frozen

private Address address;

public Account() {

}

public Account(String name, String email, Address address) {

this.name = name;

this.email = email;

this.address = address;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public Address getAddress() {

return address;

}

public void setAddress(Address address) {

this.address = address;

}

@Override

public boolean equals(Object other) {

if (other instanceof Account) {

Account that = (Account) other;

return Objects.equal(this.name, that.name) && Objects.equal(this.email, that.email);

}

return false;

}

@Override

public int hashCode() {

return Objects.hashCode(name, email);

}

}

ORMClient类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

import java.util.ArrayList;

import java.util.List;

import com.datastax.driver.core.Cluster;

import com.datastax.driver.core.Host;

import com.datastax.driver.core.Metadata;

import com.datastax.driver.core.Session;

import com.datastax.driver.mapping.Mapper;

import com.datastax.driver.mapping.MappingManager;

import com.google.common.util.concurrent.ListenableFuture;

public class ORMClient {

private Cluster cluster;

private Session session;

Mapper<Account> mapper;

public Session getSession() {

return this.session;

}

/**

* 连接集群,创建执行cql的session对象。

*

* @param node

*/

public void connect(String node) {

cluster = Cluster.builder().addContactPoint(node).build();

Metadata metadata = cluster.getMetadata();

System.out.printf("Connected to cluster: %s\n", metadata.getClusterName());

for (Host host : metadata.getAllHosts()) {

System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n", host.getDatacenter(),

host.getAddress(), host.getRack());

}

session = cluster.connect();

System.out.println();

mapper = new MappingManager(getSession()).mapper(Account.class);

}

public void insert() {

Phone phone = new Phone("home", "707-555-3537");

List<Phone> phones = new ArrayList<Phone>();

phones.add(phone);

Address address = new Address("25800 Arnold Drive", "Sonoma", 95476, phones);

Account account = new Account("John Doe", "jd@example.com", address);

mapper.save(account);

}

public void select() {

Account whose = mapper.get("jd@example.com");

if (whose == null) {

System.out.println("Account is null");

return;

}

System.out.println("Account name: " + whose.getName());

// 异步查询

ListenableFuture<Account> future = mapper.getAsync("jd@example.com");

try {

whose = future.get();

System.out.println("getAsync, Account name: " + whose.getName());

}

catch (Exception e) {

e.printStackTrace();

}

}

public void delete() {

Account account = new Account("John Doe", "jd@example.com", null);

mapper.delete(account);

}

public void update() {

// 没有看到mapper对象关于update的api

}

public void close() {

session.close();

cluster.close();

}

public void dropSchema() {

session.execute("DROP KEYSPACE complex;");

}

public static void main(String[] args) {

ORMClient client = new ORMClient();

try {

client.connect("127.0.0.1");

client.insert();

client.select();

client.delete();

client.select();

client.dropSchema();

}

catch (Exception e) {

e.printStackTrace();

}

finally {

client.close();

}

}

}

运行打印:
Connected to cluster: Test Cluster
Datacenter: datacenter1; Host: /127.0.0.1; Rack: rack1

Account name: John Doe
getAsync, Account name: John Doe
Account is null

看到文档最后,还有一个通过注解@Accessor来做查询的,好像更便利,like this:

1

2

3

4

5

6

7

8

@Accessor

public interface UserAccessor {

@Query("SELECT * FROM complex.users WHERE id = ?")

User getOnePosition(UUID userId);

......

}

下篇文章说这个注解@Accessor的用法。


相关文章
|
消息中间件 Java 测试技术
SpringBoot整合RabbitMQ图文过程以及RabbitTemplate常用API介绍
SpringBoot整合RabbitMQ图文过程以及RabbitTemplate常用API介绍
579 0
|
前端开发 应用服务中间件 Linux
nginx解决springcloud前后端跨域问题,同时配置ssl
nginx解决springcloud前后端跨域问题,同时配置ssl
374 0
|
NoSQL Java
简析Cassandra的BATCH操作
cassandra中批量写入的操作称为batch,通过batch操作可以将多个写入请求合并为一个请求。这样有如下作用: 把多次更新操作合并为一次请求,减少客户端和服务端的网络交互。 batch中同一个partition key的操作具有隔离性。
7061 0
|
11月前
|
JSON 监控 API
使用Zabbix API
使用Zabbix API
662 67
|
算法 安全 Java
三种方法教你实现多线程交替打印ABC,干货满满!
本文介绍了多线程编程中的经典问题——多线程交替打印ABC。通过三种方法实现:使用`wait()`和`notify()`、`ReentrantLock`与`Condition`、以及`Semaphore`。每种方法详细讲解了实现步骤和代码示例,帮助读者理解和掌握线程间的同步与互斥,有效解决并发问题。适合不同层次的开发者学习参考。
827 11
Angular 中的响应式表单:监听变化
Angular 中的响应式表单:监听变化
180 0
|
移动开发 缓存 前端开发
H5画布 canvas(三)canvas 库 Konva.js 的使用
H5画布 canvas(三)canvas 库 Konva.js 的使用
1865 0
H5画布 canvas(三)canvas 库 Konva.js 的使用
|
存储 达摩院 Cloud Native
基于Ganos轨迹引擎的运输车辆到达性分析
本文介绍了由阿里巴巴达摩院数据库与存储实验室研发的多模态时空数据库Ganos轨迹引擎在运输车辆位置分析中的应用场景。Ganos通过在数据库中原生内置移动对象的存储、检索与分析能力,打造了全球首个移动对象数据库,为交通、物流、出行、生活服务类客户提供海量轨迹数据的分析挖掘能力。通过阅读本文,用户可以更好的理解Ganos轨迹模型的存储结构与轨迹引擎的相关能力,助力业务开发走向便捷。
|
存储 开发框架 安全
【C++ 线程】深入理解C++线程管理:从对象生命周期到线程安全
【C++ 线程】深入理解C++线程管理:从对象生命周期到线程安全
1038 0
|
SQL 关系型数据库 MySQL
[MySQL]——SQL预编译、动态sql
[MySQL]——SQL预编译、动态sql
884 0