Java toObject() for Strings that are printed from toString() - java

The component I'm working on is changing its datastore from mongo -> mysql. In mongo, you can fit a pojo (with other pojo fields) into a document, not in mysql.
For a particular Object, I'd like to be able to toString() it and store that in a mysql TEXT column.
When I retrieve it, I'd like to be able to MyClass.staticToObject(String stringifiedObj) to get a MyClass instance. Is this possible?
I know I can write a custom toString() and parser but it seems a little tedious/prone to errors.
Is there a faster way?

Use any JSON library Guava, Jackson f.i. Serialize it to JSON -> store to DB -> retrieve -> deserialize. I think it's pretty common use case for NOSQL DBs. And for you needs you could add 2 static methods to pojo toJson/fromJson.

Related

Best way to convert Cassandra ResultSet to java objects in OSS driver

We are in the process of migrating from Cassandra DSE to OSS driver and the pain point is converting the result set into a list of Java objects. I don't want to use Mapper annotation, like detailed here
So what is the most efficient way to convert ResultSet into list of java objects? Any suggestion highly appreciated
If you don't want to use Mapper then just need to write converting function that will take Row, extract all necessary columns, and return POJO constructed from teh extracted data... I don't see other ways, except writing an adhoc version of object mapper that would use the reflection to match POJO's field names with the column names

Mapping neo4j ogm query results to java objects

I'm collecting infos from a neo4j db, but the values I return are picked out from multiple nodes, so what I'm basically returning is a table with some properties. For this example, let's say I return the properties color:String, name:String, count:String. I query these results using session.query(*QUERY*, queryParams).
Now, when I get the results, I want to map it to an existing Java Object, that I created to hold this data. This is kind of different to the 'normal' mapping, as in general, you want to map your graph nodes to objects that represent those nodes. Here, my POJOs have nothing to do with the graph nodes.
I managed to do this using custom CompositeAttributeConverter classes for each of my data-objects, but I feel there must be a better solution than writing a new class for every new object.
You might want to take a look at executing arbitrary Cypher queries using the Session object. You can get an Iterable<Map<String,Object>> from the returned Result object, which you could process over or just output to a collection of Map results.
Or, if you have APOC Procedures installed, you can always write up a query to return your results as a JSON string, and convert that to JSON objects in Java with the appropriate library and use those as needed.

How to persist a sub-document of arbitrary data to MongoDB using Spring Data?

I am trying to insert a document(json string) in a mongo db. One of the key "profile" of this has a value which is a json string. So, basically its a nested json structure. I know its possible to insert a nested json by abusing collection-refs / one-may relationships in the document class.
The issue I am facing here is that the json structure of the nested part is not fixed and hence cannot be abstracted to a java class as it is a custom data json fetched from social networking APIs. Defining "profile" as Java string inserts profile data with slashes thus escaping the double-quotes, curly brackets, etc. in json data .
Is there any other way without casting it to another object.
The way to go is probably to make profile a Map<String, Object> in the containing class. This way, you can store arbitrary data within it.
class MyDocument {
Map<String, Object> profile;
}
The answer of using a Map was a little unclear to me... how do you convert an arbitrary JSON String to a Map in a way that Spring Data will persist it as-is?
I found that using a property of type "com.mongodb.DBObject" works. Then set your property using JSON.parse:
profile = (DBObject) JSON.parse(arbitraryJSONString)

Parsing a cypher query result (JSON) to a Java object

I use the jersey/jackson stack to address a neo4j database via the REST api, but I have some issues how to interpret the result.
If I read the node by its ID (/db/data/node/xxx) the result can be mapped to my DTO very easy by calling readEntity(MyDto.class) on the response. However, usage of internal IDs is not recommended and various use cases require to query by custom properties. Here cypher comes into play (/db/data/cypher).
Assuming a node exists with a property "myid" and a value of "1234", I can fetch it with the cypher query "MATCH (n {myid: 1234}) RETURN n". The result is a JSON string with a bunch of resources and eventually the "data" I want do unmarshall to a java object. Unmarshalling it directly fails with a ProcessingException (error reading entity from input stream). I see no API allowing to iterate the result's data.
My idea is to define some kind of generic wrapper class with an attribute "data", giving this one to the unmarshaller, and unwrapping my DTO afterwards. I wonder if there is a more elegant way to do this, like using "RETURN n.data" (which does not work) or something like this. Is it?
You should look into neo4j 2.0 where return n just returns the property map.
I usually tend to deserialize the result as a nested list/map (i.e. have ObjectMapper read to Object.class or Map.class) structure and grab the data map directly out of that.
There's probably a way to tell jackson to ignore all the information around that data field
If you want to have a nicer presentation you can also check out my cypher-rs project which returns only the data in question, nothing more.

save object in db as-is or as json?

I have an object that its content I want to save in mysql. What I'm doing now is convert it to JSON and write it as text. If I need to read it I decode the json and create the same object. But I saw that I can save the object to mysql db as Object and read it as object, then cast it to my class. I do not need to have the ability to search in the json.
lets say this is my object:
class bus extends car{
private int seats;
private Person driver;
public bus(Person driver){
super();
this.seats = 50;
this.driver = driver;
}
}
So what is the preferred way(time, coding, memory usage etc..)?
And what is the correct way to save this kind of object in mysql db?
Rather than saving it as JSON you could use xstream and serialize your class to xml, which can then be saved as 'clob' to the database. Once you deserialize using xstream it will give back the object so you don't have to do manual conversion. xstream also supports serializing to json as well.
http://x-stream.github.io/
http://x-stream.github.io/json-tutorial.html
If you do not need options provided by this format than consider to use standard way - binary format based on serialization
There are benefits
Very less space consuming
No need third party libs
Out of box solution, because of java
Consider to use special ORM tools for this reason. It will dramatically simplify your task and save your time.
There are ORM tools
1. Hibernate
2. MyBatis
3. Eclipse link
4. Spring jdbc
Using one of them let you concentrate on a business points rather than on a low level concepts

Categories