Netbeans creating "JPA Controller classes from entity classes" - java

I want to achieve basic CRUD operations available of the db schema I already have for a JAVA program. To put it in another way, I have a DB schema I use with PHP and I just need them to be entities available in a JAVA application. I discovered I can use Netbeans and sucessfully created Entities from DB!
(Entities look like this: http://pastebin.com/f601b9218)
However when I try to create New > JPA controllers from entity classes in Netbeans I got empty JPA controller classes like:
package javaapplication3;
public class CustomerJpaController {
}
It is empty :) I was expecting CRUD functions inside the generated JPA controller classes as I read from examples and tutorials.
What could be the reason of empty JPA controller classes? Is there any other easy way for me to "just" match DB tables with JAVA classes for basic CRUD operation. (I wish there could be easy way to achieve active record pattern)
Thanks in advance.

Usually, I never like to go too much with the wizard thing. But it seems like it should generate the basic CRUD operations, though. I don't know exactly which tutorial you followed. Right now, I am looking at this. After reading this I am getting the same impression, by the way. But may be it just generates the empty classes, and nothing else. I am not sure never tried to do that.
However, coding it yourself would be quite simple, I believe. Especially when you already got the NamedQueries defined for your entities.

Related

How to map custom data structures to bean entities with JPA/Hibernate?

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.

Including only individual entities in Spring Boot JPA Test

I am trying to test jpa queries in a separate projects entities by quickly kicking off a spring boot project to generate a platform to insert data into a H2 database, run queries against it, and validate the results of these queries.
Because the separate project has a large entity base, I'd like to selectively pick out the entities that I want to per test.
I've tried to use the #EntityScan annotation for this, but it seems designed to pull entire packages, even if you just specify a class.
This strikes me as something that there must be a solution for, but I have so far been unable to find it.
The thing is that when you set up a test class with a Spring context, that context exists for all the tests in that class, unless you use #DirtiesContext or some other trick to make it rebuild itself.
#EntityScan(basePackageClasses = MyEntity.class)
The code above doesn't tell Spring to use MyEntity, it tells it to start searching for entities in the package that MyEntity exists in. It also does so recursively, so if you have for instance:
com.example.entities.MyEntity
com.example.entities.subpackage.MyOtherEntity
It would pick up both MyEntity and MyOtherEntity. If, however, you wrote your EntityScan like this:
#EntityScan(basePackageClasses = MyOtherEntity.class)
Then MyEntity would not be found.
With that in mind, the only suggestion I have for you is perhaps to group your large number of entities into multiple smaller subpackages to make it easier to load, if loading all of them at once is indeed a showstopper for you.
So, I came up with a solution using Hibernate specific code. The Hibernate SessionFactoryBeans have an addAnnotatedClass method, so if you create a LocalSessionFactoryBean bean in your configuration file, you can just pass in the individual classes that you want. If you get a little creative, you can add the classes you want to test (I also have a DependencyGrapher that lets me know all the entity classes I need to pull in) as #TestPropertySource's in your test class and reference those values in the set up code.
It's actually pretty easy if you are using Hibernate, which, unfortunately, I am not able to do. I'm constrained to use EclipseLink, which just doesn't seem to offer this out of the box. I think I have a lead with Spring's PersistenceUnitPostProcessor though.

Do you write Hibernate code inside POJOs?

We have a web application which uses JSP, Servlet and Hibernate. The design pattern we got is MVC like, which means,
JSP -> Servlet -> Beans (POJO)
Now the question. Once of out developers has inserted the hibernate queries, hibernate session creation etc inside POJOs. Now inside these POJOs, there are methods like getAllEmployees(), getAllAgents() etc. This made it extremely hard for us to change the database tables (we handle database manually, using MySQL Workbench) and use automatic tools to re-generate the POJOs because these methods will be lost.
Now there are 2 arguments. One is that this maintaining hibernate queries, sessions inside POJOs is a good work, because it seems like pure MVC. The other argument is move the hibernatre code to Servlets and call the POJOs just like beans, only to set and get values.
We have not worked in Hibernate before. From above 2, what is the preferred place to write hibermnate code when it comes to hibernate?
Finally, please note we are not interested in Spring or other frameworks, we use pure JSP and Servlet with Hibernate
Probably, what you need is another layer of abstraction. Since your pojos are recreated after new migrations, you shouldn't insert code in it (I don't agree with that aproach, but that's just my opinion :-) )
JSP -> Servlet -> NewLayer -> POJO
I don't know where you put your business rules, but in this scenario it will be in the "NewLayer" wich would consist of a "hibrid" layer of service and dao.
I would recommend these readings to rethink your actual architecture:
https://softwareengineering.stackexchange.com/questions/220909/service-layer-vs-dao-why-both
Responsibilities and use of Service and DAO Layers

How do I Implement this design to remove code repetition

My application has about 50 entities that are displayed in grid format in the UI. All 50 entities have CRUD operations. Most of the operations have the standard flow
ie. for get, read entities from repository, convert to DTO and return a list of DTO's.
for create/update/delete - get DTO's - convert to entities, use repository to create/update/delete on DB, return updated DTOs
Mind you that for SOME entities, there are also some entity specific operations that have to be done.
Currently, we have a get/create/update/delete method for all our entities like
getProducts
createProducts
updateProducts
getCustomers
createCustomers
updateCustomers
in each of these methods, we use the Product/Customer repository to perform the CRUD operation AFTER conversion from entity -> dto and vice versa.
I feel there is a lot of code repetition and there must be a way by which we can remove so many of these methods.
Can i use some pattern (COMMAND PATTERN) to get away with code repetition?
Have a look at the Spring Data JPA or here project. It does away with boilerplate code for DAO.
I believe it basically uses AOP to interpret calls like
findByNameandpassword (String name,String passwd)
to do a query based upon the parameters passed in selecting the fields in the method name (only an interface).
Being a spring project it has very minimal requirements for spring libraries.
Basically, you have 2 ways to do this.
First way: Code generation
Write a class that can generate the code given a database schema.
Note that this you will create basic classes for each entity.
If you have custom code (code specific to certain entities) you can put that in subclasses so that it doesn't get overwritten when you regenerate the basic classes.
Object instatiation should be via Factory methods so that the correct subclass is used.
Make sure you add comments in the generated code that clearly states that the code is generated automatically (so that people don't start editing them directly).
Second way: Reflection
This solution, while being more elegant, is also more complex.
Instead of generating one basic class for each entity you have one basic class that can handle any entity. The class would be using reflection to access the DTO:s.
If you have custom code (code specific to certain entities) you can put that in other classes. These other classes would be injected into the generic class.
Using reflection would require a strict naming policy on your DTO:s.
Conclusion
I have been in a project using the first method in a migration project to generate DTO classes for the service interface between the new application server (running java) and the fat clients and it worked quite well. We had more than 100 generated DTO classes. I am aware that what you are attempting is slighty different. Editing database records is a generic problem (all projects need it) but there aren't (m)any frameworks for it.
I have been thinking about creating a generic tool or framework for it but I have never gotten around to it.

How do I use JPA to make library objects database persistent?

I've been using JPA on a small application I've been working on. I now have a need to create a data structure that basically extends or encapsulates a graph data structure object. The graph will need to be persisted to the database.
For persistable objects I write myself, it is very easy to extend them and have the extending classes also persist easily. However, I now find myself wanting to use a library of graph related objects (Nodes, edges, simple graphs, directed graphs, etc) in the JGrahpT library. However, the base classes are not defined as persistable JPA objects, so I'm not sure how to get those classes to save into the database.
I have a couple ideas and I'd like some feedback.
Option 1)
Use the decorator design pattern as I go along to add persistence to an extended version of the base class.
Challenges:
-- How do I persist the private fields of a class that are needed for it to be in the correct state? Do I just extend the class add an ID field, and mark it as persistable? How will JPA get the necessary fields from the parent class? (Something like ruby's runtime class modification would be awesome here)
-- There is a class hierarchy (Abstract Graph, Directed Graph, Directed Weighted Graph, etc.). If I extend to get persistence, extending classes still won't have the common parent class. How do I resolve this? (Again, Something like ruby's runtime class modification would be awesome here)
Option 2) Copy paste the entire code base. Modify the source code of each file to make it JPA compatible.
-- obviously this is a lot of work
I'm sure there are other options.. What have you got for me SO???
Do the base classes follow the JavaBeans naming conventions? If so you should be able to map them using the XML syntax of JPA.
This is documented in Chapter 10 of the specification:
The XML descriptor is intended to
serve as both an alternative to and an
overriding mechanism for Java language
metadata annotations.
This XML file is usually called orm.xml. The schema is available online
Your options with JPA annotations seem pretty limited if you're working with a pre-existing library. One alternative would be to use something like Hibernate XML mapping files instead of JPA. You can declare your mappings outside of the classes themselves. Private fields aren't an issue, Hibernate will ignore access modifiers via reflection. However, even this may end up being more trouble than its worth depending on the internal logic of the code (Hibernate's use of special collections and proxies for instance, will get you in hot water if the classes directly access some of their properties instead of using getter methods internally).
On the other hand, I don't see why you'd consider option 2 'a lot of work'. Creating a ORM mapping isn't really a no brainer task no matter how you go about it, and personally I'd consider option 2 probably the least effort approach. You'd probably want to maintain it as a patch file so you could keep up with updates to the library, rather than just forking.

Categories