I am working on an application that directly uses Java MongoDB driver for Mongo queries.
I’d like to use Morphia to map retrieved Documents to my POJOs and vice versa (but I do not want to do queries through Morphia itself).
I am trying to achieve this with Morphia 1.1, however the fromDBObject in this version requires Morphia’s DataStore as an argument (previous versions did without it) – and I do not want to give Morphia actual connection to the database. I am not using references to join data from different collections – so when transforming an already retrieved document to POJO it is not needed to retrieve any additional data from the DB.
Can I achieve this in the version 1.1 (eg. by creating and passing an empty, nonfunctional datastore (how to create it?), or just by passing null)?
If not, I can live with the older (1.0.1) version – but does that make sense?
And if not – what would be the best solution for mapping POJOs to Mongo documents – are there any other, currently maintained, libraries to achieve this?
And, again, if not – what would be the best way to implement this functionality myself? The solution should be as generic as possible regarding document and POJO classes schema, I am OK with annotating my entity classes.
Did you try passing in null for the Datastore? It's used for resolving any #Referenced fields for the most part. You should be fine just passing null. But as always, "try it and see."
Related
I am having a data base call which is in Oracle and i am using Spring data JPA for that.
I do have a function which utilizes this db call to retrieve the result every time in the loop.
Now my problem is most of the time the combination of parameter values are repeating. How to avoid this and is there a way to store temporarily for the given set of combination and the corresponding result set without any caching mechanism.
Any luck in Java 8 or spring data JPA itself?.
You have various options.
If you are using Hibernate you may use it's query cache: https://vladmihalcea.com/how-does-hibernate-query-cache-work/ I'm not sure if EclipseLink has a similar feature.
You may use Springs caching facility. https://spring.io/guides/gs/caching/
And of course you may role your own by assembling all the parameters in a single object with proper equals and hashCode implementation and store the result in a HashMap
We have a (possibly large) custom data structure implemented in Java (8+). It has a simple and optimal API for querying pieces of data. The logical structure is roughly similar to an RDMS (it has e. g. relations, columns, primary keys, and foreign keys), but there is no SQL driver.
The main goal is to access the data via ORM (mapping logical entities to JPA annotated beans). It would be nice if we could use JPQL. Hibernate is preferred but other alternatives are welcome too.
What is the simplest way to achieve this? Which are the key parts of such an implementation?
(P. S. Directly implementing SessionImplementor, EntityManagerImplementor etc. seems to be too complicated.)
You have two possibilities.
Implement a JDBC compliant driver for your system, so you can use a JPA implementation such as Hibernate "directly" (although you may need to create a custom dialect for your system).
Program directly against the JPA specification like ObjectDB does, which bypasses the need to go through SQL and JPA implementations completely.
The latter one is probably easier, but you'd still need to implement the full JPA API. If it's a custom in-house-only system, there's very little sense in doing either one.
One idea I thought up just now, that I feel may work is this:
Use an existing database implementation like H2 and use the JPA integration with that. H2 already has a JPA integration libraries, so it should be easy.
In this database, create a Java stored procedure or function and call it from your current application through JPA. See this H2 documentation on how to create a Java stored procedure or function. (You may want to explore the section "Using a Function as a Table" also.)
Define a protocol for the service methods and encapsulate it in a model class. An instance of this model class may be passed to the function/SP and responses retrieved.
Caveat: I have never done this myself but I think it will work.
Edit: Here is a diagram representing the thought. Though the diagram show H2 separately, it will most probably be in the same JVM as "Your Java/JEE application". However, since it is not necessary to use H2, I have shown it as as separate entity.
The actual use case i'm working on has many classes that should be persisted (basically different sensor types). Currently i have to create the table per hand for every sensor type. Isn't there a mechanism of the driver that could auto create the respective tables if they are not existent (like seen in e.g. Hibernate)?
This would allow me to deploy the app on other systems without need for recreating the tables again. Furthermore this is quite handy for quick prototyping ;)
I created a partial solution to the problem - a table / udt create-query creation facility. It can be found here:
https://gist.github.com/eintopf/3ae360110846cb80a227
Unfourtunately the type mapping is NOT complete at the moment, since the respective type mapper class in the object mapper package of datastax is private.
The program just builds all CREATE queries and one use them like he wants (copy paste into cqlsh or use it directly on the cassandra session via Java).
Not at the moment, but this is a planned feature (JAVA-569).
I am developing an application in Flex, using Blaze DS to communicate with a Java back-end, which provides persistence via JPA (Eclipse Link).
I am encountering issues when passing JPA entities to Flex via Blaze DS. Blaze DS uses reflection to convert the JPA entity into an ObjectProxy (effectively a HashMap) by calling all getter methods on the entity. This includes any lazy-initialised one/many-to-many relationships.
You can probably see where I am going. If I pass a single object through JPA this will call all one/many-to-many methods on this object. For each returned object if they have one/many-to-many relationships they will be called too. As such, by passing back a single JPA entity I actually end up doing multiple database calls and passing all related entries back as a single ObjectProxy instance!
My solution to date is to create a translator to convert each entity to an ObjectProxy and vice-versa. This is clearly cumbersome and there must be a better way.
Thoughts please?
As an alternative, you could consider using GraniteDS instead of BlazeDS: GraniteDS has a much more powerful data management stack than BlazeDS (it competes more with LCDS) and fully support lazy-loading for all major JPA engines: Hibernate, EclipseLink, OpenJPA, etc.
Moreover, GraniteDS has a great client-side transparent lazy loading feature and even a so-called reverse lazy-loading mechanism.
And you don't need any kind of intermediate DTOs: it serializes JPA entities as is and uses code-generated ActionScript beans on the client-side to keep their initialization states.
Unfortunately, lazy-loading is not easy to accomplish with Flash clients. There are some working solutions, like dpHibernate, but so far all the different solutions I have tested fall short of what you would expect in terms of performance and ease of use.
So in my experience, it is the best and most reliable solution to always use DTOs, which adds the benefit of cleanly separating the database and view layers. This necessitates, though, that you implement either eager loading, or a second server round trip to resolve your many-to-many relations, as well as a good deal more boilerplate code to copy the DAO and DTO field values.
Which one to choose depends on your use case: Sometimes getting only the main object's fields might be enough, then you could simply omit the List of related objects from your DTO (transfer only those values you need for your query). Sometimes you may actually need the entire list of related entities, and then you could get it via eager loading, or by setting up a second remote object to find only the list.
EclipseLink also provides a copyObject() API that allows you to give a copy group of exactly what attribute you want. You could then use this copy to avoid having the relationships that you do not want.
If you have a detached object, you could just null out the fields that you do not want as well, or use a DTO.
I am new to Java, and am working on a Public Transit Java app as a first small project.
I am loading transit data in from a server through an XML api (using the DOM XML API). So when you call a constructor for say a BusStop(int id), then the constructor loads the info about that Stop from the server based on the id provided. So, I am wondering about a couple things: how can I make sure I don't instantiate two BusStop objects with the same id (I just want one object for each BusStop)?
Also does anyone have recommendations on how I should load up the objects, so I don't need to load the whole database every time I run the app, just the BusStop, and relevant Arrivals and BusTrips objects for that stop? I have done C++ and MVC PHP programming previously, but haven't had experienced loading large numbers of objects with circular object references etc.
Thanks!
I wouldn't start the download/deserialization proces in a constructor. I would write a manager class per entity type with a method to fetch a Java object for a given entity based on its ID. Use a HashMap with the key type as your entity ID and the value type as the Java class for that object. The manager would be a singleton using your preferred pattern (I would probably use static members for simplicity).
The first thing the fetch method should do is check the map to see if it contains an entry for the given ID. If it has already fetched and build this object, return it. If it has not, fetch the entity from the remote service, deserialize the object appropriately, load it into the HashMap by the specified ID, and return it.
Regarding references to other object I suggest you represent those as IDs in your Java objects rather than storing them as Java object references and deserializing them at the same time as the referencing object. The application can lazily instantiate those objects on demand through the relevant manager. This reduces problems through circular references.
If the amount of data is likely to exceed available RAM on your JVM you'd need to consider periodically removing older objects from the map to recover memory (confident they would be reloaded when required).
For this application I would use the following Java EE technologies: JAX-RS, JPA and JAXB. You will find these technologies included in almost every Java application server (i.e. GlassFish).
JPA - Java Persistence API
Provides a simple means of converting your objects to/from the database. Through annotations you can mark a relationship as lazy to prevent the entire database from being read. Also through the use of caching database access and object creation is reduced.
JAXB - Java Architecture for XML Binding
Provides a simple means of converting your objects to/from XML. An implementation is included in Java SE 6.
JAX-RS - Java API for RESTful Services
Provides a simple API (over HTTP) for interacting with XML.
Example
You can check out an example I posted to my blog:
Part 1 - The Database
Part 2 - Mapping the Database to JPA Entities
Part 3 - Mapping JPA entities to XML (using JAXB)
Part 4 - The RESTful Service
Part 5 - The Client
For the classes you want to load only once per given id, use some kind of Factory design pattern. Internally you may want to store id to instance mapping in a Map. Before actually fetching the data from server, first do a lookup on this map to see if you already have a class loaded for this id. If not then go ahead with fetching and the update the map.