No converter found capable of converting from type org.bson.types.ObjectId to type int (help) - spring-data-mongodb

I am using Spring data and mongodb to get all test data using this function:
when I run this
List<Test> tests = mongoOps.findAll(Test.class);
for(Test test : tests){
log.info(test.toString());
}
my document:
{
"_id" : ObjectId("56a09fd614923217ac1c545f"),
"id" : 1.0,
"address" : [
1.0,
2.0,
3.0
]
}
my Test class
#Document(collection = Test.COLLECTION_NAME)
public class Test {
public static final String COLLECTION_NAME = "test";
#Id
private int id;
private List<Double> address;
public Test(int id, List<Double> address) {
super();
this.id = id;
this.address = address;
}
}
Error:
No converter found capable of converting from type org.bson.types.ObjectId to type int
How to fix that?

Your id property is not the identifier of the document in the database. _id is. You should be able to read this by tweaking your domain class to:
class Test {
#Id ObjectId databaseId;
int id;
…
}
#Id references the document identifier, which in your case is an ObjectId. Read more on that in the Spring Data MongoDB reference documentation

Related

SpringBoot : RestAPI Returning JSON Array But I want value with label to set in AngularJS

Requirement:
Trying to populate all UNIQUE record in Angular Drop Down List
I am using predefined Table have already data.
REST API URL => http://localhost:8080/getAllCategory
Facing Problem:
API is giving the reponse in JSON Array like [xxx,yyyy,zzzz]. So I am thinking if I can convert JSON Array with some label value which can solve my problem.
Either any other way to get over with this issue.
Note :
If I am not using the native query and using the below code then I am getting all the table value in JSON with label and populating all the record in drop down but I want only UNIQUE
#Repository
public interface CategoryRepository extends JpaRepository<ccCategory,Integer>
{}
My Implementation :
Model :
#Table(name = "cccategory")
public class ccCategory
{
#Id
#Column(name = "[catid]")
public Integer catID;
#Column(name = "[categoryname]")
public String categoryName;
#Column(name = "[active]")
public int active;
public ccCategory() {
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
}
Repository:
#Repository
public interface CategoryRepository extends JpaRepository<ccCategory,Integer>
{
public static final String FIND_CATEGORYNAME = "SELECT DISTINCT catID,categoryName from ccCategory";
#Query(value = FIND_CATEGORYNAME, nativeQuery = true)
List<ccCategory> getByactive(int active);
}
Controller :
#GetMapping("/getAllCategory")
public List<Object> getAllCategory() {
// public List<ccCategory> getAllCategory() {
System.out.println("***** Call : API getAllCategory() ******");
List<Object> cCategory = categoryRepository.getCategoryName();
return categoryData;
}

Serializing childdocuments, fields spring data solr

I am trying to persist nested documents in solr. I have tried both Field(child= true) and #Childdocument annotation.
With #Field(child=true) & #ChildDocument i get
[doc=null] missing required field: id, retry=0 commError=false
errorCode=400
I tried #Indexed with #Id. Also tried to specify required = false.
#Service
public class NavigationMapper implements DocumentMapper<Navigation> {
#Override
public SchemaDefinition getSchemaDefinition() {
SchemaDefinition sd = new SchemaDefinition();
sd.setName(Navigation.class.getSimpleName());
sd.setFields(new ArrayList<>());
for(Method method : Navigation.class.getDeclaredMethods()){
if(method.getName().startsWith("get") && method.getParameterCount() <= 0){
SchemaDefinition.FieldDefinition fd = new SchemaDefinition.FieldDefinition();
String fieldName = method.getName().replace("get", "");
fd.setName(fieldName.replace(fieldName.charAt(0), fieldName.toLowerCase().charAt(0)));
fd.setRequired(false);
fd.setStored(true);
sd.getFields().add(fd);
}
}
return sd;
}
With #Field i get the package name in the stored value :
activePage:
["org.apache.solr.common.SolrInputField:activePage=Page(id=blt6134c9cf711a7c27,
and get below error while i try to read in my rest controller.
No converter found capable of converting from type [java.lang.String]
to type [com.blizzard.documentation.data.shared.model.page.Page]
I did a lot of reading about this and haven't been able to successfully configure and persist the nested document in SolrDb. I read that i could use SolrJConverter for this , but not sucessfull with it either. Is there any working example i can refer to or tutorial about this feature?
#Data
#SolrDocument(collection = "Navigation")
public class Navigation implements Serializable {
#Id
//#Indexed(required = false)
private String id;
#Field
#Indexed(name = "path", type = "string")
private String path;
#ChildDocument
private Page navigationRoot;
#ChildDocument
private Page activePage;
}
#Data
#SolrDocument(collection = "Page")
public class Page implements Serializable {
#Id
// #Indexed(name= "id", type="string", required = false)
private String id;
#Field
#Indexed(name= "path", type="string")
private String path;
#Field
private PageContentType contentType;
#ChildDocument
private List<Page> children;
#Indexed("root_b")
private boolean root;
}
I expect to store the nested document inthe solrDb.

SolrJ only value of enum type

I'm trying to add documents to Solr using SolrJ. Here is my class with #Field annotations:
public class Popular {
#Field("popular_id")
private Long popularId;
#Field("type")
private Type type;
public Long getPopularId() {
return popularId;
}
public void setPopularId(Long popularId) {
this.popularId = popularId;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
And here is my enum:
public enum Type {
SERVICE,
BRAND,
CITY
}
Here is my method that adds documents to Solr using SolrJ:
private void addPopularItem(SolrClient client, Long popularId, String[] wordsArray)
throws IOException, SolrServerException {
Popular popular = new Popular();
popular.setPopularId(popularId);
popular.setType(Type.valueOf(wordsArray[1]));
client.addBean(popular);
}
And my document is Solr looks like that:
{
"popular_id":[1],
"**type**":["com.XXX.XXX.XXX.indexes.popular.Type:SERVICE"],
"id":"7306406f-4b99-4cee-9c9a-0b7ee84cd5b9",
"_version_":1584849462071656448,
"type_str":["com.XXX.XXX.XXX.indexes.popular.Type:SERVICE"]
}
Is there a way to change that type field so it has only value from Type enum instead of package + class name + value?

Unable to retrieve data from SQLite database because of table's name.(Hibernate)

I have a tabe in my database with name "Group".
This is my model code:
#Entity
#Table(name="Group")
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="group_id")
private int id;
#Column(name="name")
private String name;
#Column(name="color")
private String color;
public Group(){
this(null,null);
}
public Group(String name, String color){
this.name=name;
this.color=color;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
I'm trying to retrieve data from database using:
Session session=mainApp.getSessionFactory().openSession();
groupList=FXCollections.observableArrayList(session.createCriteria(Group.class).list());
groupPicker.setItems(groupList);
session.close();
But it gives me an error(SQL error or missing database (near "Group": syntax error)). I know that it is happening because hibernate generates query similar to this: SELECT * FROM Group. To work properly it should be: SELECT * FROM "Group", but I do not know how to achieve this.
After I tried several different ways, I finally came up with a solution, which works. I just changed my model's table name to:#Table(name="\"Group\"").
If You are using XML somehow You can be interested in element delimited-identifiers to force quoting of all entities. More can be found Hibernate, MySQL and table named "Repeat" - strange behaviour

Query document in list - spring data mongodb

I have the following object:
{
"id" : "sampleId";
foos : [{
"prop1":"value1",
"prop2":"value2"
},
{
"prop1":"value3",
"prop2":"value4"
}
]}
How can I get foos, where prop2 is value4? I'm using Spring data mongodb.
If you use spring data mongodb repositories, it can make your life easy. You will need a domain class. e.g.
public class Foo {
String prop1;
String prop2;
}
public class MyClass {
String id;
List<Foo> foos;
}
public interface MyClassRepository extends MongoRepository<MyClass, String> {
List<MyClass> findByFoosProp2(String prop2ValueToLookFor);
// assuming you can find multiple matches
}
Then simply call this method from your code
public clsss SomeBusinessClass {
#Autowired
private MyClassRepository repository;
public void mySomeBusinessMethod() {
List<MyClass> myObjects = repository.findByFoosProp2("value4");
}
}
This code will return a SampleBean with id sampleId wich will have only matching items in collection foos.
// Match one document with sampleId
Query q1 = new Query(where("id").is("sampleId"));
// match only foos with prop2 value value2
Query q2 = query(where("foos").elemMatch(where("prop2").is("value2))
BasicQuery query = new BasicQuery(q1.getQueryObject(), q2.getQueryObject());
SampleBean result = mongoTemplate.findOne(query, SampleBean.class)

Resources