How to create Java POJO class dynamically? - java

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).

Related

Android/Java best up to date mapper

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.

JPA, Start with entities vs database schema

Which is better when using JPA, especially when starting a new project?
Start with designing entities and then let JPA generate the database or
Start with the database schema and let tools generate entity classes?
im part of a small company. im both the software developer and DBA. i have complete freedom for the application and db design
im just starting the project
If you want to design a database, then start with the schema. If you want to write software, then start with the entities. The point of an ORM is to let you think about an object model without having to worry about the database that stores it, so questions of this type actually confuse the issue somewhat by insinuating crossover between the realms. Are you a software developer or a DBA? That, much more than the fact that you're using JPA, is what will determine the correct answer for you.
Um - neither? The power of JPA is that you don't have to generate one from the other! Generation of entities or database schema might be a good starting place if you have one already in place; but the generated stuff is not something you will want to use long term.
You cannot simply design one side of the mapping without any consideration of the other. If you will share the database with other applications, you will need to give more weight to the database schema. If your application has a complex model, you will want to focus on the object model first, allowing it to be driven by the use cases you uncover as you develop your application.
I tend to start with the object model first (even without a backing database to start) because that allows me to see the application in action earlier and get a feel for what we really want to build. But integration with the database must happen earlier rather than later; as its constraints will quickly impose themselves on your object model. :-)
It depends on one's needs . Usually in a product development environment , there are different teams which work on database design , interface design and implementation . So in that case , you have no option than generating the JPA entities from the already database design.
Secondly , if you are starting from the scratch and you know what are you upto then you can probably start writing your own entities (java class) and then generate the database from that.
Better go for database Scheme. Because some of the features r not available in JPA generated database.In JPA We cant give default values for our column. Check HERE for the allowable attributes in JPA.
Its upto you. whether to go top-down or bottom up approach. In case this schema would be exclusive to your application, see how your team members and analysts understand ORM or DB. In my experience analysts are better understand in terms of tables. But if they are good to discuss in terms of classes or UML diagrams go with JPA. Also, take into consideration views of your DBA and build engineer.
If you have complete flexibility and are not restricted to a DB schema and want a clean object model in your java application then start with with the model first and generate the schema from the model. This also allows you to generate clean JSON representations from the clean model to serve as on-the-wire format for your objects using technologies like Jackson (or GSON).
Doing DB Schema first and reverse engineering model classes from it will result in relational concepts seeping into your model classes resulting in poor (polluted) model.
In summary do model first unless your hands are tied and you must map to some existing schema.

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.

Transparently storing class state without exposing implementation

I have a model (MVC) class whose internal state (which basically contains of private int fields) I want to store.
The program is running on Android (for now) so I need to store the in a Bundle, but I'll be using the same class later in a desktop application where I'll have to store the state some other way, so I can't reference Bundle directly in my class.
So my question is: What is the best way to store (and retrieve) the state of a class without exposing it's implementation?
The best I could think of removing the private access modifier so that the fields become package accessible and create read/write helper classes in the same package, but that somehow seems wrong.
I'm not familiar with the persistence mechanisms on Android, but in general, it's a good idea to separate your persistence logic (i.e. the code that stores objects' state) from the domain objects that actually contain the data. That's the approach taken by JPA and virtually all modern object-relational mapping tools in Java, for example. So yes, referencing Bundle objects directly in your domain classes doesn't sound like the right strategy, especially if you plan to use the same classes in a non-Android environment, too.
My advice is to serialize the object state into XML, which is portable across environments. There are lots of open source tools available that help make this easy and don't require any special code in your domain classes. The two I'm most familiar with are JiBX and Castor. I don't know if either will work on Android, but even if Android has its own tools to transform objects to and from XML, you still might be able to use JiBX or Castor on the desktop side, since they can adapt to many different XML formats.
Once you have the data in XML form, you can persist it using whatever means is most appropriate on the target environment. On the desktop app, that probably means files in the user's home directory. On Android, I guess it would be bundles, but that's not my area of expertise. Good luck!
Take a look at the bridge pattern, as well: http://en.wikipedia.org/wiki/Bridge_pattern
As Rob said, you need to decouple the persistence from the data objects, so you can handle data uniformly and use a bridge to handle the persistence in different platforms.

Databases and Java

I am starting out writing java code and interacting with databases for my "nextbigthing" project. Can someone direct me towards the best way to deal with adding/updating tables/records to databases? Here is my problem. There is too much repitition when it comes to DB code in java. I have to create the tables first (I use mysql). I then create classes in Java for each table. Then I create a AddRow, DeleteRow, UpdateRow and Search* depending on my need. For every table, every need creating this huge ass sql statement and the classes all seems like a huge waste of my time. There has to be a better, easier, more efficient way of doing things. Is there something out there that I do not know that will let me just tell Java what the table is and it automatically generate the queries and execute them for me? Its simple SQL that can be auto generated if it knows the column names and DB table inter dependencies. Seems like a very reasonable thing to have.
Check out Hibernate - a standard Java ORM solution.
User hibernate for mapping your classes to Database.
Set its hbm2ddl.auto to update to avoid writing DDL yourself. But note that this is not the most optimal way to take it to production.
Consider using Hibernate:
https://www.hibernate.org/
It can create java classes with regular CRUD methods from existing database schema.
Of course there is a much better way !
You really want to learn some bits of Java EE, and in particular JPA for database access.
For a complete crash course on Java EE, check out the Sun the Java EE 5 tutorial.
http://java.sun.com/javaee/5/docs/tutorial/doc/
Part 4 - Enterprise Beans
Part 5 - Persistence (JPA)
Then you want to try Hibernate (for instance) which has an implementation of JPA.
This is for Java 5 or later.
If you are still in Java 2, you might want to try Hibernate or iBatis.
You can also try iBatis, if you want control over SQL. Else JPA is good.
You can also try using Seam Framework. It has good reverse-engineering tools.
There is also torque (http://db.apache.org/torque/) which I personally prefer because it's simpler, and does exactly what I need.
With torque I can define a database with mysql(Well I use Postgresql, but Mysql is supported too) and Torque can then query the database and then generate java classes for each table in the database. With Torque you can then query the database and get back Java objects of the correct type.
It supports where clauses (Either with a Criteria object or you can write the sql yourself) and joins.
It also support foreign keys, so if you got a User table and a House table, where a user can own 0 or more houses, there will be a getHouses() method on the user object which will give you the list of House objects the user own.
To get a first look at the kind of code you can write, take a look at
http://db.apache.org/torque/releases/torque-3.3/tutorial/step5.html which contains examples which show how to load/save/query data with torque. (All the classes used in this example are auto-generated based on the database definition).
Or, if Hibernate is too much, try Spring JDBC. It eliminates a lot of boilerplate code for you.
iBatis is another good choice, intermediate between Spring JDBC and Hibernate.
It's just a matter of using the right tools. Use an IDE with tools to autogenerate the one and other.
If you're using Eclipse for Java EE and decide to head to JPA, then I can recommend to take benefit of the builtin Dali plugin. There's a nice PDF tutorial out at Eclipse.org.
If you're using Eclipse for Java EE and decide to head to "good ol" Hibernate, then I can recommend to take benefit of the Hibernatetools plugin. There's good reference guide out at Hibernate.org.
Both tools are capable of reverse-engineering from a SQL table to fullworthy Javabeans/entities and/or mapping files. It really takes most of boilerplate pains away. The DAO pattern is slightly superflous when grabbing JPA. In case of Hibernate you can consider to use a Generic DAO.

Categories

Resources