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

如果说,入门二的用法是hibernate,那么这篇入门三的用法就更像ibatis。

完整的代码请参考:https://github.com/yankai913/cassandra-java-userguide。

由于本文复用了入门二的部分代码,所以这里只贴新增的。

新增表:

1

2

3

4

5

CREATE TABLE complex.users (

id uuid PRIMARY KEY,

name text,

addresses map<text,frozen<address>>

);

UserAccessor类:

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

import java.util.Map;

import java.util.UUID;

import com.datastax.driver.core.ResultSet;

import com.datastax.driver.mapping.Result;

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

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

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

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

import com.zoo.Address;

@Accessor

public interface UserAccessor {

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

User getOnePosition(UUID userId);

@Query("SELECT * FROM complex.users")

Result<User> getAll();

@Query("SELECT * FROM complex.users")

ListenableFuture<Result<User>> getAllAsync();

@Query("insert into complex.users(id, name, addresses) values (:id, :name, :addresses)")

ResultSet insertUser(@Param("id") UUID id, @Param("name") String name,

@Param("addresses") Map<String, Address> addresses);

@Query("UPDATE complex.users SET name= :name WHERE id= :id")

ResultSet updateName(@Param("id") UUID id, @Param("name") String name);

@Query("UPDATE complex.users SET addresses[:name]=:address WHERE id= :id")

ResultSet updateAddress(@Param("id") UUID id, @Param("name") String addressName,

@Param("address") Address address);

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

ResultSet deleteOne(UUID userId);

}

User类:

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

import java.util.Map;

import java.util.UUID;

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

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

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

import com.zoo.Address;

import com.zoo.BaseEntity;

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

public class User extends BaseEntity {

private UUID id;

private String name;

@Column(name = "addresses")

@Frozen("map<text,frozen<address>>")

private Map<String, Address> address;

public UUID getId() {

return id;

}

public void setId(UUID id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Map<String, Address> getAddress() {

return address;

}

public void setAddress(Map<String, Address> address) {

this.address = address;

}

}

BaseEntity类,就是做了toString()重写:

1

2

3

4

5

6

7

8

9

10

import com.alibaba.fastjson.JSON;

public class BaseEntity {

@Override

public String toString() {

return JSON.toJSONString(this);

}

}

测试类AccessorClient:

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

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.UUID;

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.MappingManager;

import com.datastax.driver.mapping.Result;

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

import com.zoo.Address;

import com.zoo.Phone;

/**

*

* @author yankai913@gmail.com

* @date 2015-11-4

*

*/

public class AccessorClient {

private Cluster cluster;

private Session session;

// 放一个公共userId

private UUID userId = UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25");

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();

}

public void insert() {

MappingManager manager = new MappingManager(getSession());

UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);

Map<String, Address> addresses = new HashMap<String, Address>();

Address address = new Address();

address.setCity("Honolulu");

address.setStreet("123 Arnold Drive");

address.setZipCode(95476);

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

Phone phone1 = new Phone("job1", "10086");

Phone phone2 = new Phone("job2", "10000");

phones.add(phone1);

phones.add(phone2);

address.setPhones(phones);

addresses.put("Work", address);

userAccessor.insertUser(userId, "tom", addresses);

}

public void select() {

// getAll

MappingManager manager = new MappingManager(getSession());

UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);

Result<User> users = userAccessor.getAll();

for (User user : users) {

System.out.println("getAll:" + user);

}

// getOne

User user = userAccessor.getOnePosition(userId);

System.out.println("getOne:" + user);

// getAllAsync

ListenableFuture<Result<User>> future = userAccessor.getAllAsync();

try {

for (User _user : future.get()) {

System.out.println("getAsync:" + _user);

}

}

catch (Exception e) {

e.printStackTrace();

}

}

public void update() {

MappingManager manager = new MappingManager(getSession());

UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);

userAccessor.updateName(userId, "jack");

}

public void update2() {

MappingManager manager = new MappingManager(getSession());

UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);

Address address = new Address();

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

Phone phone2 = new Phone("job2", "10010");

phones.add(phone2);

address.setPhones(phones);

userAccessor.updateAddress(userId, "Work", address);

}

public void delete() {

MappingManager manager = new MappingManager(getSession());

UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);

userAccessor.deleteOne(userId);

}

public void dropSchema() {

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

}

public void close() {

session.close();

cluster.close();

}

public static void main(String[] args) {

AccessorClient client = new AccessorClient();

try {

client.connect("127.0.0.1");

client.select();

client.insert();

client.select();

client.update();

client.select();

client.update2();

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

getOne:null

getOne:{“address”:{“Work”:{“city”:”Honolulu”,”phones”:[{"alias":"job1","number":"10086"},{"alias":"job2","number":"10000"}],”street”:”123 Arnold Drive”,”zipCode”:95476}},”id”:”fbdf82ed-0063-4796-9c7c-a3d4f47b4b25″,”name”:”tom”}

getOne:{“address”:{“Work”:{“city”:”Honolulu”,”phones”:[{"alias":"job1","number":"10086"},{"alias":"job2","number":"10000"}],”street”:”123 Arnold Drive”,”zipCode”:95476}},”id”:”fbdf82ed-0063-4796-9c7c-a3d4f47b4b25″,”name”:”jack”}

getOne:{“address”:{“Work”:{“phones”:[{"alias":"job2","number":"10010"}],”zipCode”:0}},”id”:”fbdf82ed-0063-4796-9c7c-a3d4f47b4b25″,”name”:”jack”}

getOne:null


上一篇:搭载hexo+github博客系统


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