Operaciones CRUD con mongodb
Publicado por Camilo (20 intervenciones) el 06/06/2021 01:52:10
Estoy tratando de insertar un objeto tipo Owner a una coletion de la base de datos "4Citizens", segui este tutorial https://mongodb.github.io/mongo-java-driver/4.2/driver/getting-started/quick-start-pojo/. El problema esta en que me dice que no encuentra "codec" para la clase Owner:
(No se si el punto al final de la clase Owner tiene algo que ver o no en el sentido que intenta hacer cast a la clase que no es)
Sin embargo en la clase OwnerService creo toda esta configuración de acuerdo al tutorial. Aqui la clase:
Y aqui hago el llamado del método "create":
Acá esta la clase OwnerPOJO:
De antemano Gracias.
1
2
3
18:38:16,088 INFO [org.mongodb.driver.cluster] (default task-1) Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
18:38:16,090 INFO [stdout] (default task-1) Error while creating owner: Can't find a codec for class com.example.demo.persistance.entities.Owner.
(No se si el punto al final de la clase Owner tiene algo que ver o no en el sentido que intenta hacer cast a la clase que no es)
Sin embargo en la clase OwnerService creo toda esta configuración de acuerdo al tutorial. Aqui la clase:
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
public class OwnerService {
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
public OwnerService(){
CodecRegistry codecRegistry= fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoClientSettings mongoClientSettings= MongoClientSettings.builder().codecRegistry(codecRegistry).build();
mongoClient= MongoClients.create(mongoClientSettings);
mongoDatabase= mongoClient.getDatabase("4Citizens").withCodecRegistry(codecRegistry);
}
public boolean create(Owner owner){
try{
MongoCollection<Owner> ownerMongoCollection= mongoDatabase.getCollection("owner", Owner.class);
ownerMongoCollection.insertOne(owner);
ownerMongoCollection.find().forEach(System.out::println);
return true;
}catch (Exception e){
System.out.println("Error while creating owner: " +e.getMessage());
return false;
}finally {
mongoClient.close();
}
}
}
Y aqui hago el llamado del método "create":
1
2
3
4
5
6
7
8
9
@GET
@Produces("text/plain")
public String hello() {
Owner owner= new Owner("asdf", 0, "asdf", "ne", "nei");
if(ownerService.create(owner)){
return "Hello, World!";
}else
return "a";
}
Acá esta la clase OwnerPOJO:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Owner {
private String id;
private int personId;
private String name;
private String address;
private String neighborhood;
public Owner(String id, int personId, String name, String address, String neighborhood) {
this.id = id;
this.personId = personId;
this.name = name;
this.address = address;
this.neighborhood = neighborhood;
}
}
De antemano Gracias.
Valora esta pregunta


0