The only thing different here is the initial setup, you need to provide a list of jars from your WEB-INF/lib as well as the path to WEB-INF/classes since these aren't on the default java.class.path.
There are two ways to get this to work:
Way 1: Pass in the class names for all your entities
The advantage to this is that you don't need the ServletContext or anything, just the one method:
entityManagerFactory = EntityManagerFactoryEntityManagerFactoryImpl.newInstanceWithClassNames(persistenceUnitName, null, setOfClassName);
Way 2: Add Extra Webapp Class Paths
The advantage to this one is that you don't need to let SimpleJPA know about new entities or anything, it will just automagically find them.
This method will get you all the paths you need.
private static Set<String> getLibPaths(ServletContext servletContext) {
String basePath = servletContext.getRealPath("");
Set<String> libPathsLocked = servletContext.getResourcePaths("/WEB-INF/lib");
Set<String> libPaths = new HashSet<String>();
if(libPathsLocked != null){
for (String s : libPathsLocked) {
// need to prefix with full path
libPaths.add(basePath + s);
}
}
String path = servletContext.getRealPath("/WEB-INF/classes");
if (path != null) {
File fp = new File(path);
if (fp.exists()) libPaths.add(path);
}
return libPaths;
}This isn't in the SimpleJPA package because it adds a dependency on the servlet api.
Now all you need to do is create your EntityManagerFactory with the following constructor:
entityManagerFactory = new EntityManagerFactoryImpl(persistenceUnitName, null, libPaths);
TODO: Explain SimpleJPAUtil usage.
Just a FYI if anyone is working with MyFaces?. To get the servletContext you need to use FacesContext?.getCurrentInstance().getExternalContext().getContext()
How do you get the ServletContext? in JBoss?
Just a snippet for 'Way 2' (without simplejpa.properties files):
private static EntityManagerFactoryImpl factory; @Override public void init(ServletConfig config) throws ServletException { super.init(config); Map<String,String> props = new HashMap<String,String>(); props.put("accessKey","<key>"); props.put("secretKey","<secret_key>"); factory = new EntityManagerFactoryImpl("UnitName", props, getLibPaths(config.getServletContext())); }May be it would be usefull.
Here's a simple tutorial to using SimpleJPA as a web service. This was useful for people who are noobs to Java Spring.
http://vulab.com/blog/2009/03/05/amazon-simpledb-web-service-with-simple-jpa-typica-using-java-programming-language/
It was also helpful because I read through all the docs on persistence and this example showed just how easy it was to do.
Is there a simple way to add the Libs from the enclosing ear in which the webapp is packaged?
How can I limit the folders that the EntityManager? scans?
For e.g, I have com.company.hibernate.model and I have com.company.simpledb.model
I am trying to get the entitymanager to scan only the com.company.simpledb.model.
How can I do that?