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的用法。


上一篇:cassandra入门(三):便捷的@Accessor注解


下一篇:cassandra入门(一):jdbc连接cassandra作增删改查