How to expose a MySQL database as OData
I've figured out how to do it - using odata4j. I've documented my steps below in case anyone else wants to do something similar.
You will need to:
- generate a JPA model from your database
- use odata4j's NorthwindJpaProducerExample.java script
Detailed steps are below:
- Odata4j is an open-source Odata Producer/Consumer in Java. Therefore, you will need to set up Eclipse for EE Developers with a database. I suggest this tutorial if you are new to Eclipse.
- Follow these instructions to generate a JPA model.
- Go to Odata4j and download the latest archive zip
- Add odata4j-bundle-x.x.jar to your build path (it is found in the bundles file).
- Insert the following scripts from Odata4j, found on their github: NorthwindJpaProducerExample, JPAProvider, and DatabaseUtils (requires slf4j). (To be honest, I just copy and pasted them into Eclipse). At this point, your Project Explorer bar should look like this (without model.main):
At this point, right-click the project and select Build Path > Configure Build Path. Add the following "External Jars" from your Odata4j archive file.
Now edit the code in NorthwindJpaProducerExample in the following ways:
- Change the string "endpointUri" to whatever url you want the oData at
- Change the string "persistenceUnitName" to the name of your entity in persistence.xml (as you can in the image above, mine was called "createJPA".)
And then you have OData!
I ran in to a couple problems while following these steps and will document them here in case you have them also.
- In order to successfully follow step 2 (generate JPA) each table MUST have a primary key. Do it - I'm not joking.
- After editing the code, I had a "BigInteger" error. JPAProducer does not support bigInteger field types. Go back to your database and change the size of your column to a regular int.
- After changing your database in ANY manner, make sure to refresh you database and to clean the project. This will make you and Eclipse happy.
- I don't think this will be necessary for everyone, but I did need to add a HyperSQL driver dependency. If you get a HSQL error, go to here and get the latest stable version. Add the hsqldb.jar to your Build Path.
Not SUPER easy, but a lot better than a 70+ page manual.