Skip to content

Commit c149d80

Browse files
author
Josh Smith
committed
Updated to include change streams
1 parent 74717dc commit c149d80

File tree

8 files changed

+224
-4
lines changed

8 files changed

+224
-4
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.mongodb.ms0.example.springdata;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Bean;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.data.mongodb.core.MongoTemplate;
7+
import org.springframework.data.mongodb.core.messaging.DefaultMessageListenerContainer;
8+
import org.springframework.data.mongodb.core.messaging.MessageListenerContainer;
9+
10+
@Configuration
11+
public class ChangeStreamConfig {
12+
13+
14+
@Autowired
15+
MongoTemplate template;
16+
17+
18+
19+
20+
21+
22+
}
Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,53 @@
11
package com.mongodb.ms0.example.springdata;
22

3+
import com.mongodb.client.model.changestream.ChangeStreamDocument;
4+
import com.mongodb.ms0.example.springdata.models.Customer;
5+
import com.mongodb.ms0.example.springdata.services.ChangeStreamListener;
6+
import org.bson.Document;
7+
import org.springframework.beans.factory.annotation.Autowired;
38
import org.springframework.boot.SpringApplication;
49
import org.springframework.boot.autoconfigure.SpringBootApplication;
10+
import org.springframework.context.ConfigurableApplicationContext;
11+
import org.springframework.context.annotation.Bean;
12+
import org.springframework.data.mongodb.core.MongoTemplate;
13+
import org.springframework.data.mongodb.core.messaging.*;
14+
15+
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
516

617
@SpringBootApplication
718
public class SpringDataApplication {
819

20+
@Bean
21+
MessageListenerContainer messageListenerContainer(MongoTemplate template) {
22+
return new DefaultMessageListenerContainer(template);
23+
}
24+
25+
26+
27+
928
public static void main(String[] args) {
10-
SpringApplication.run(SpringDataApplication.class, args);
29+
ConfigurableApplicationContext context = SpringApplication.run(SpringDataApplication.class, args);
30+
31+
MongoTemplate template = context.getBean(MongoTemplate.class);
32+
MessageListenerContainer container = context.getBean(MessageListenerContainer.class);
33+
ChangeStreamListener listener = context.getBean(ChangeStreamListener.class);
34+
35+
ChangeStreamRequest<Customer> request = ChangeStreamRequest.builder()
36+
.collection("customers")
37+
.publishTo(listener)
38+
.database("providerPref")
39+
.filter()
40+
.build();
41+
42+
container.register(request, Customer.class);
43+
container.start();
44+
45+
46+
47+
48+
49+
50+
1151
}
1252

1353
}

spring-data/src/main/java/com/mongodb/ms0/example/springdata/controllers/CustomerController.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.mongodb.ms0.example.springdata.models.Customer;
44
import com.mongodb.ms0.example.springdata.services.CustomerService;
55
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.data.domain.Page;
67
import org.springframework.http.MediaType;
78
import org.springframework.web.bind.annotation.*;
89

@@ -24,6 +25,11 @@ public Customer getCustomerById(@PathVariable("id") String id) {
2425
return customer.orElse(null);
2526
}
2627

28+
@GetMapping
29+
public Page<Customer> getAllCustomers() {
30+
return service.getAllCustomers(1);
31+
}
32+
2733
@PostMapping
2834
public Customer createCustomer(@RequestBody Customer customer) {
2935
return service.createCustomer(customer);
@@ -36,4 +42,10 @@ public List<Customer> customerSearch(@RequestBody Map<String, String> values) {
3642
}
3743

3844

45+
@PatchMapping(value="{id}")
46+
public Customer updateCustomer(@PathVariable("id") String id, @RequestBody Customer customer){
47+
return service.updateCustomer(id, customer);
48+
}
49+
50+
3951
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.mongodb.ms0.example.springdata.models;
2+
3+
import org.bson.types.ObjectId;
4+
import org.springframework.data.mongodb.core.mapping.Document;
5+
6+
import java.util.Date;
7+
import java.util.HashMap;
8+
import java.util.Set;
9+
10+
@Document("customer_history")
11+
public class CustomerAudit {
12+
13+
private ObjectId id;
14+
private HashMap<String, Object> fields;
15+
private Date changedDate;
16+
17+
public CustomerAudit(){
18+
this.changedDate = new Date();
19+
this.fields = new HashMap<>();
20+
}
21+
22+
23+
public HashMap<String, Object> getFields() {
24+
return fields;
25+
}
26+
27+
public void setFields(HashMap<String, Object> fields) {
28+
this.fields = fields;
29+
}
30+
31+
public Date getChangedDate() {
32+
return changedDate;
33+
}
34+
35+
public void setChangedDate(Date changedDate) {
36+
this.changedDate = changedDate;
37+
}
38+
39+
public ObjectId getId() {
40+
return id;
41+
}
42+
43+
public void setId(ObjectId id) {
44+
this.id = id;
45+
}
46+
}

spring-data/src/main/java/com/mongodb/ms0/example/springdata/repository/CustomerRepository.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import org.springframework.data.mongodb.repository.Aggregation;
55
import org.springframework.data.mongodb.repository.MongoRepository;
66
import org.springframework.data.mongodb.repository.Query;
7+
import org.springframework.data.mongodb.repository.Update;
8+
import org.springframework.data.repository.query.Param;
79
import org.springframework.stereotype.Repository;
810

911
import java.util.List;
@@ -21,4 +23,8 @@ public interface CustomerRepository extends MongoRepository<Customer, String> {
2123
@Query("{ 'id' : ?0 }")
2224
Optional<Customer> findById(String id);
2325

26+
@Query("{ 'id': ?2 }")
27+
@Update("{'$set': {'firstName': ?0, 'lastName': ?1}}")
28+
long updateCustomer(String firstName, String lastName, String id);
29+
2430
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.mongodb.ms0.example.springdata.services;
2+
3+
import com.mongodb.client.model.changestream.ChangeStreamDocument;
4+
import com.mongodb.ms0.example.springdata.models.Customer;
5+
import com.mongodb.ms0.example.springdata.models.CustomerAudit;
6+
import org.bson.Document;
7+
import org.springframework.data.mongodb.core.MongoTemplate;
8+
import org.springframework.data.mongodb.core.messaging.Message;
9+
import org.springframework.data.mongodb.core.messaging.MessageListener;
10+
import org.springframework.stereotype.Component;
11+
12+
13+
14+
@Component
15+
public class ChangeStreamListener implements MessageListener<ChangeStreamDocument<Document>, Customer> {
16+
17+
18+
private MongoTemplate template;
19+
20+
21+
public ChangeStreamListener(MongoTemplate template){
22+
super();
23+
this.template = template;
24+
}
25+
26+
27+
28+
@Override
29+
public void onMessage(Message<ChangeStreamDocument<Document>, Customer> message) {
30+
System.out.println(message.getBody().getFirstName());
31+
CustomerAudit audit = new CustomerAudit();
32+
if (message.getRaw().getUpdateDescription() != null) {
33+
for (String key : message.getRaw().getUpdateDescription().getUpdatedFields().keySet()) {
34+
audit.getFields().put(key, message.getRaw().getUpdateDescription().getUpdatedFields().get(key).asString());
35+
}
36+
template.insert(audit);
37+
}
38+
39+
}
40+
}

spring-data/src/main/java/com/mongodb/ms0/example/springdata/services/CustomerService.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
11
package com.mongodb.ms0.example.springdata.services;
22

33
import com.mongodb.ms0.example.springdata.models.Customer;
4+
import com.mongodb.ms0.example.springdata.models.CustomerAudit;
45
import com.mongodb.ms0.example.springdata.repository.CustomerRepository;
6+
import org.bson.types.ObjectId;
57
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.data.domain.Page;
9+
import org.springframework.data.domain.PageRequest;
10+
import org.springframework.data.domain.Pageable;
11+
import org.springframework.data.mongodb.core.MongoTemplate;
12+
import org.springframework.data.mongodb.core.query.Criteria;
13+
import org.springframework.data.mongodb.core.query.Query;
14+
import org.springframework.data.mongodb.core.query.Update;
615
import org.springframework.stereotype.Service;
16+
import org.springframework.transaction.annotation.Transactional;
717

818
import java.util.List;
919
import java.util.Optional;
@@ -14,6 +24,9 @@ public class CustomerService {
1424
@Autowired
1525
private CustomerRepository repository;
1626

27+
@Autowired
28+
private MongoTemplate template;
29+
1730

1831
public Optional<Customer> getCustomerById(String id) {
1932
return repository.findById(id);
@@ -27,4 +40,44 @@ public Customer createCustomer(Customer customer) {
2740
public List<Customer> customerSearch(String name) {
2841
return repository.customerSearch(name);
2942
}
43+
44+
@Transactional
45+
public Customer updateCustomer(String id, Customer customer) {
46+
47+
Query query = new Query();
48+
query.addCriteria(Criteria.where("_id").is(id));
49+
Update update = new Update();
50+
update.set("firstName", customer.getFirstName());
51+
update.set("lastName", customer.getLastName());
52+
53+
CustomerAudit audit = new CustomerAudit();
54+
//audit.setId(new ObjectId("65280bf1e618e05b7f569a28"));
55+
audit.getFields().put("firstName", customer.getFirstName());
56+
audit.getFields().put("lastName", customer.getLastName());
57+
58+
template.save(audit);
59+
60+
61+
template.updateFirst(query, update, Customer.class);
62+
return template.findById(id, Customer.class);
63+
64+
65+
66+
/*
67+
long updated = repository.updateCustomer(customer.getFirstName(), customer.getLastName(), id);
68+
if (updated > 0) {
69+
return customer;
70+
} else {
71+
return null;
72+
}
73+
*/
74+
75+
76+
77+
}
78+
79+
public Page<Customer> getAllCustomers(int page){
80+
Pageable pageable = PageRequest.of(0,10);
81+
return repository.findAll(pageable);
82+
}
3083
}

spring-data/src/main/resources/application.properties

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
#spring.data.mongodb.uri=mongodb+srv://<username>:<password>@cluster0.g8fm0.mongodb.net/mygrocerylist?retryWrites=true&w=majority
66

77
#Local MongoDB - no authentication
8-
spring.data.mongodb.uri=mongodb://localhost:27017/ms0
8+
#spring.data.mongodb.uri=mongodb://localhost:27017/ms0
9+
spring.data.mongodb.uri=mongodb+srv://pov_user:[email protected]/providerPref?retryWrites=true&w=majority
910

1011

11-
logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG
12-
logging.level.org.mongodb.driver=DEBUG
12+
logging.level.org.springframework.data.mongodb.core=DEBUG
13+
logging.level.org.mongodb.driver=INFO

0 commit comments

Comments
 (0)