response.setStatus(200);
response.setContentType("text/html");
writer = response.getWriter();
writer.println("<html><head><title>Using JPA in Phobos JavaScript</title>");
writer.println("</head><body><center><h2>Java Persistence API usage in Javascript.</h2></center>");
// get the entity manager based on the Persistence Unit name (declared in the persistence.xml file)
var em;
try {
var emf = Packages.javax.persistence.Persistence.createEntityManagerFactory("jpaExample1-pu", null);
em = emf.createEntityManager();
} catch (exception) {
var exceptionMsg = exception.description;
if (exception.description == null) {
exceptionMsg = exception.message;
}
if (exceptionMsg.indexOf("DatabaseException") != -1) {
writer.println("<p><br><br>Please ensure that the database is up and running");
} else if (exceptionMsg.indexOf("NullPointerException") != -1) {
writer.println("<p><br><br>Please ensure that the JPA application is built and the jar is present in the classpath of the phobos server");
}
}
if (em != undefined) {
// Insert some Authors if none are defined
var authors = em.createQuery("select a from Author a").getResultList().toArray();
if (authors.length==0){
var tx = em.getTransaction();
tx.begin();
var author = new Packages.jpaexample.Author();
author.name ="Danny Goodman"; //equivalent to author.setName("Danny Goodman");
author.organisation= "O\'Reilly";
em.persist(author);
writer.println("<br><br>created one author named "+ author.name);
var author2 = new Packages.jpaexample.Author();
author2.name= "Paul Wilton";
author2.organisation ="Wrox Press Inc";
em.persist(author2);
writer.println("<br><br>created one author named "+ author2.name);
tx.commit();
}
// List out the Authors that are available
authors = em.createQuery("select a from Author a").getResultList().toArray();
writer.println("<h3>List of Authors as of "+ java.util.Date() +"</h3>")
writer.println("<table><tr><th>Id</th><th>Name</th><th>Organisation</th></tr>")
for (var i in authors) {
var a = authors[i];
writer.println("<tr><td>" + a.authorId
+ "</td><td>" + a.name
+ "</td><td>" + a.organisation
+ "</td></tr>");
}
writer.println("</table>")
}
writer.println("</body></html>");
writer.flush();
You need to create an account or log in to post comments to this site.