Android/Java best up to date mapper - java

In my Android app I need to perform some mappings between aplication layers. Mainly between DTOs and instances of domain classes.
So I've been looking for mappers, which could do my life easier, but most articles I have found are pretty old and they describes deprecated mappers oftentimes, like
Dozer
Nomin
Transmorph
Model Bridge
So far I found only 2 up to date mappers, such as
mapStruct
model mapper
I'm confused which one to choose and is there a better mapper, which will fit my needs?
Basically I need mapper with simple and understandable API, whithout tonns of ugly code which I'll need to write to work with it.

Well, in my project I use ModelMapper.
It is simple to start. And it has nice documentation and broad functionality. Also, its advantage is in conventional mapping.
Here you will find plenty of examples using it.
EDIT:
As I can see, you provided link to GitHub repository of this project in the question.

MapStruct is a great fit for Android apps (disclaimer: MapStruct project lead here) as it isn't a runtime library but a code generator that works at compile time.
I.e. you don't need to add any library to your app but will only add the generated mapper implementions. Resulting in a smaller app size and a great performance, too, as there is no reflection or runtime byte code generation involved, instead plain Java getter/setter calls. Which also makes mappings very easy to debug if needed.

Related

#Autowired vs XML

I'm new to Spring and DI in general. But from what I have read, DI affords you the ability to swap out implementations very easily using frameworks like Spring. I can understand value there when it comes to XML bean configuration because code doesn't need to be changed at all for accomplishing switchable implementations. But if we're using annotations like #Autowired or #Qualifier...we would need to change the code. So why do we want to use annotations over XML-based configuration?
This was actually a topic of lively conversation around the time that Spring 3.0 came out in 2009 and JavaConfig was added to the core system base.
In theory, being able to externalize application setup is a great thing. However, it turns out that in practice there are two distinct groups of setup choices: the application shape or dependency graph, and particular values like API keys, database connection strings, and so on that vary between environment but usually don't change the way that the beans are wired.
Experience has shown that the dependency graph, which is essentially what you'd express in XML, is almost never changed without also making changes to the accompanying implementation code anyway, so there is very little real-world benefit to defining the graph in XML. On the other hand, writing #Bean methods in Java means that it's a lot easier to test configuration when needed, the compiler can ensure type safety, and decision logic (such as conditionals) are simpler to implement.
Furthermore, the availability of annotations means that it's possible to extend the domain-specific language for configuration fairly easily in Java--just create a new annotation and its accompanying processor (such as #ConditionalOnProperty); Spring Boot itself is an extreme example of the flexibility of this model. In XML, on the other hand, injecting new tags or attributes into a schema is a lot more of a hassle.
There are times when XML may still be the better choice (I've particularly gone with it for writing out Spring Integration pipelines, which can be easier to read in XML than in the Java DSL), but the real-world benefits turned out not to be all that valuable in most cases, and the safety and flexibility of configuration as code has won out.
This is not must, you have to choices to use Annotations or XML its up to you but Annotations is easy to use, faster and more readable than configurations, and when you use it you will find all the information in a single file, but it also have disadvantages.
Annotations preferable
Use Annotations in anything that is stable and defines the core
structure of the application. Anything that would need a code change
is okay to sit as an annotation.
I recommended you to read the following links for more info :
xml-configuration-versus-annotation-based-configuration
spring-framework-xml-vs-annotations

Cross-framework Solutions for field Annotations

Does anyone have any strategies or examples of cross-framework libraries?
I am working on a project with an android app, a java server and a Java desktop client, which all use different frameworks. I need to refactor some core business logic into a separate library that can be used across all of these to ensure consistent behavior, but the field annotations are killing me.
The problem is that I am using Room in the Android app (which requires the #PrimaryKey annotation on the primary key field of a database entity) and JPA in the server and JavaFX client (which requires #Id).
Given this level of difficulty with the models, we initially copy-pasted the fields without annotations to the others when changing them. However, the business logic needs to make use of the models and accommodate each platform's specific ORM, Http client and Json serializer. (I know that it is technically possible to get Gson, Apache Http and Hibernate to run on all of these platforms, but actually doing any of these solutions created too many nightmares of its own)
As far as I can tell, there isn't a nice solution to this. Fortunately, the same #Inject is used in Dagger2 and CDI/CDI-SE so I have created some interfaces that each platform/framework will implement.
Does anybody have any examples or case studies I could look at which might help me arrive at a solution?
(I realize this question doesn't include any code samples, but it's more of a general programming strategy question.)
Disclaimer: I am the architect of JDX for Java and JDXA for Android ORMs.
You may consider using JDX for Java and JDXA for Android ORM frameworks to share the common object model, the core business logic code, and the data integration code across Java server, Java desktop, and Android platforms.
JDX and JDXA don't use annotations to define the mapping - instead they use an external text file to define the mapping specification based on a simple ORM grammar. So you may use the same mapping specification for your common object model across different platforms. Also, the APIs for both JDX and JDXA are simliar.
So, you just need to use the appropriate JDX(A) ORM library for your target platform and an appropriate JDBC driver for your target database without needing to change your object model or business logic.

Hibernate objects and GWT-RPC

I want to transfer hibernate objects with GWT-RPC to the frontend. Of course i can not transfer the annotated class because the annotations can not be compiled to javascript. So i did the hibernate mapping purely in the ".hbm.xml". This worked fine for very simple objects. But as soon as i add more complex things like a oneToMany relationship realized with e.g. a set, the compiler complains about some serialization issues with the set (But the objects in the set are serializable as well).
I guess it does't work because hibernate creates some kind of special set that can not be interpreted by GWT?
Is there any way to get around this or do i need another approach to get my objects to the frontend?
Edit: It seems that my approach is not possible with RPC because hibernate changes the objects. (see answer from thanos). There is a newer approach from google to transfer objects to the the frontend: The request factory. It looks really good and i will try this now.
Edit2: Request factory works perfectly and is much more convenient than RPC!
This is a quote from GWT documentation. It says that hibernate changes the object from the original form in order to make it persistent.
What this means for GWT RPC is that by the time the object is ready to be transferred over the wire, it actually isn't the same object that the compiler thought was going to be transferred, so when trying to deserialize, the GWT RPC mechanism no longer knows what the type is and refuses to deserialize it.
Unfortunately the only way to implement the solution is by making DTOs and their appropriate converters.
Using Gilead is a cleaner approach (no need for all this DTO code), but DTOs are more ligtweight and thus produce less traffic through the wire.
Anyhow there is also Dozer, that will generate the DTOs for you so there will not be much need for yo to actually write the code.
Either way as mchq08 said the link he provided will solve many of questions.
I would also make another suggestion! Separate the projects. Create a new one as a model for your application and include the jar into the GWT. In this way your GWT project will be almost in its' entirety the GUI and the jar library can be re-used for other projects too.
When I created my RPC to Hibernate I used this example as a framework. I would recommend downloading their source code and reading the section called "Integration Strategies" since I felt the "Basic" section did not justify DTO. One thing this tutorial did not go over as well is the receiving and sending part from the web page(which converts to JS) so thats why I am recommending you downloading their source code and looking at how they send/receive each the DTOs.
Post the stack trace and some code that you believe will be useful to solving this error.
Google's GWT & Hibernate
Reading this (and the source code) can take some time but really helps understands their logic.
I used the next approatch: for each hibernate entity class I had client replica without any hibernate stuff. Also I had mechanism for copy data between client <-> server clases.
This was working, but I belive current GWT version should work with hibernate-annotated classes..
On a client project, I use Moo (which I wrote) to translate Hibernate-enhanced domain objects into DTOs relatively painlessly.

How to create Java POJO class dynamically?

I have seen a post in this website regarding the dynamic POJO generation. I have the similar requirement now.
I have some tables in the database. I want to have a POJO class for each table with fields and corresponding getters and setters. These classes are to be created dynamically. Once these classes are created I should use those setters and getters in other class to get and set the data and return the Java object.
I have seen BCEL, CGLIB and some other open source tools for this, but couldnt find the proper example. Can you help me?
Have you looked at any of the ORM (Object Relational Mapping) frameworks out there that have been created for just this purpose? Hibernate or the Java EE 6 standard JPA, for instance. It sounds like you are starting down on a path of re-inventing something that is both pretty complex and very time consuming - never a good idea.
UPDATE: in response to comment
Well, I can only say that you guys are building yourselves into a world of hurt. Consider:
If you rely on completely dynamic classes, you are you going to reference those classes and objects from other classes? Through reflection? And how are you going to keep track of all the created classes, their names and the names of their setters and getters?
What happens when you have to restart your system? How are you going to re-create all those dynamic classes?
With a completely dynamic database, how are you going to be able to do any performance optimization on it? Like indexing, for instance.
I can only strongly advise you to re-think your architecture. Dynamic datamodels are a mess to begin with, and next to impossible to maintain, optimize and debug. I've seen systems based on it and it's not pretty. IBM Lotus WCM is a prime example of data model horror. A properly designed and normalized relational model will be better in 99,99999999% of the cases.
Combining this with a harness of dynamic, run time ORM classes will be utterly impossible to maintain (and understand).

Easy Java ORM for small projects

I'm currently searching for a really easy way to get simple Java Objects persistent in Databases and/or XML and/or other types of data stores.
For big projects in the company i would use hibernate, ibatis, datanucleus or something like that. But with small private projects this will take over 80% of the worktime.
I also found "simpleORM" but this one requires to code data-related stuff pretty hardly into the data-model classes. I don't really like that style so this is no option for me.
Do you have a suggestion for some library which simply takes my objects and saves / loads them as they are or with very little configuration?
You could try my ORMLite library, which was designed as a simple replacement for hibernate and iBatis. I'm the main author. It supports a number of JDBC databases and has an Android backend. Here is the getting started section of the manual which has some code examples. Here also are working examples of simple usage patterns.
Try Norm. It's a lightweight layer over JDBC. It adds almost zero overhead to JDBC calls and is very easy to learn.
You could just serialize your objects into a file/database whatsoever.
If you want to define the mapping then you'd have to go for more configuration and the standard OR mappers out there (like Hibernate) don't really add that much on top.
You could try xstream. It's really simple OXM library working without upfront configuration.
Sample code:
XStream xstream = new XStream();
// marshalling
String xml = xstream.toXML(domainObject);
// unmarshalling
domainObject = xstream.fromXML(xml);
For relational database persistence try one of the JPA implementations, such as OpenJPA.
The setup overhead is minimal. You can let JPA to create your schema & tables for your from your object definitions, so you don't need to hand crank any sql. All you need to supply is some annotations on your entities and a single config file, persistence.xml.
You can also use jEasyORM (http://jeasyorm.sourceforge.net/).
In most cases it automatically maps objects to database tables with no need for configuration.
You may want to consider www.sormula.org. Minimal programming/annotations and simple learning curve. It uses standard SQL and JDBC so will work with any relational db.
U could try SnakeORM http://sourceforge.net/p/selibs/wiki/Home/
It doesnt have many runtime dependencies, uses JPA annotations and follows DAO pattern.
Disclosure: I am the author of this project
Well if you want an ORM, then that implies that you want to map objects to tables, columns to fields etc. In this case, if you want to avoid the hassle of bigger ORM implementations, you could just use plain old JDBC, with simple DataAccessor patterns. But then this does not translated to XML directly.
If you want to just persist the object somewhere, and only care about "understanding" the object in Java, then serialization is a simple effective method, as Thomas mentioned earlier.
You could also try my little ORM library, Java2DB. I created it specifically for small projects that just want quick and easy access to their database. Check it out on GitHub.
Onyx Database is a very feature rich Java NoSQL database alternative. It's pure java with several persisting modes (caching, embedded-database, save-to-remote, and save-to-remote-cluster. It has an embedded ORM, and is probably the easiest persistence API I've used.

Categories

Resources