1

I'm currently studying the sample code from the Boilerplates Java DB Web Starter app on bluemix and I'm having some troubles changing the table. My DB is ready and functioning there. I tried to change the code to instead of getting from the todolist table, to get from my country table. Here is the picture of how I changed it on the code:

https://i.stack.imgur.com/1jrgk.png

package example.jpa;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Country")
public class TODO {

    @Id //primary key
    @Column(name = "country_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    int id;

    @Basic
    @Column(name = "country_name")
    String name;

    public String getName() {
        System.out.println(name);
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        System.out.println(id);
        return id;
    }

    public void setId(int pk) {
        id = pk;
    }

    @Override
    public String toString() {
        return String.format("{\"id\": \"%d\", \"name\": \"%s\"}", id, name);
    }
}

http://i.imgur.com/tirtUaY.

package example.jpa;

import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/Country")
public class TODOListResource {

    private UserTransaction utx;
    private EntityManager em;

    public TODOListResource() {
        utx = getUserTransaction();
        em = getEm();
    }

    @POST
    public Response create(@FormParam("name") String name) {
        TODO todo = new TODO();
        todo.setName(name);
        try {
            utx.begin();
            em.persist(todo);
            utx.commit();
            return Response.ok(todo.toString()).build();
        } catch (Exception e) {
            e.printStackTrace();            
            return Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build();
        } finally {
            try {
                if (utx.getStatus() == javax.transaction.Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @DELETE
    public Response delete(@QueryParam("country_id") int id) {
        try {
            utx.begin();
            TODO todo = em.find(TODO.class, id);
            if (todo != null) {
                em.remove(todo);
                utx.commit();
                return Response.ok().build();
            } else {
                return Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build();
        } finally {
            try {
                if (utx.getStatus() == javax.transaction.Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @PUT
    public Response update(@FormParam("country_id") int id,
            @FormParam("name") String name) {
        try {
            utx.begin();
            TODO todo = em.find(TODO.class, id);
            if (todo != null) {
                todo.setName(name);// TODO check if null
                em.merge(todo);
                utx.commit();
                return Response.ok().build();
            } else {
                return Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build();
        } finally {
            try {
                if (utx.getStatus() == javax.transaction.Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(@QueryParam("country_id") int id) {
        if (id == 0) {
            List<TODO> list = em.createQuery("SELECT country_id, country_name FROM country", TODO.class).getResultList();
            if (list.size() == 0) {
                list = em.createQuery("SELECT country_id, country_name FROM country", TODO.class).getResultList();
            }
            //TODO use JSON util like Gson to render objects and use REST Response Writer
            String json = "{\"id\":\"all\", \"body\":" + list.toString() + "}";
            return Response.ok(json).build();
        }
        TODO todo = null;
        try {
            utx.begin();
            todo = em.find(TODO.class, id);
            utx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build();
        } finally {
            try {
                if (utx.getStatus() == javax.transaction.Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (todo != null)
            return Response.ok(todo.toString()).build();
        else
            return Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND).build();
    }

    /*private void createSampleData() {
        create("sample entry #1");
        create("sample entry #2");
        create("sample entry #3");
    }*/

    private UserTransaction getUserTransaction() {
        InitialContext ic;
        try {
            ic = new InitialContext();
            return (UserTransaction) ic.lookup("java:comp/UserTransaction");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return null;
    }


    private EntityManager getEm() {
        InitialContext ic;
        try {
            ic = new InitialContext();
            return (EntityManager) ic.lookup("java:comp/env/openjpa-todo/entitymanager");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return null;
    }

}

I also couldn't find where it's creating the table TODO when it doesn't exist in my db.

Thank you

Daiane
  • 35
  • 8
  • Can you elaborate on what troubles you're having? I don't see anything obviously wrong with your changes, so an error message would probably help. – opiethehokie Sep 30 '15 at 21:06
  • It's much better if you actually add the code itself rather than the adding the code as images. Nobody is going to type that code in. You have to make it easy for people to help you, hence the recommendation to create an [mcve](http://stackoverflow.com/help/mcve) – kkuilla Oct 01 '15 at 08:15
  • So, I edited my question adding the codes. I have a table on bluemix named country with two columns: country_id (int) and country_name (varchar). I downloaded the JavaDB web starter sample code and when I ran, it created the todolist table on my db. What I'm trying to do with the code is to understand how does it interacts with my db, So I wanted to change the todolist table to my country table. I did these modifications that I showed in the two classes and now it's giving me an error. I'm a beginner on bluemix and I'm trying to create an app with java and db. Appreciate the help. :) – Daiane Oct 01 '15 at 12:40

1 Answers1

3

Table creation is configured in the boilerplate's persistence.xml file. JPA can create it for you, so the app isn't explicitly doing it. Depending on which Liberty JPA feature you use (because they use different JPA implementations) one of these properties is needed:

<!-- allow table definitions/creation on-the-fly jpa-2.0 feature -->
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<!-- allow table definitions/creation on-the-fly jpa-2.1 feature -->
<property name="eclipselink.ddl-generation" value="create-tables"/>
opiethehokie
  • 1,862
  • 11
  • 14
  • Thanks for your answer. Yes but it doesn't use sql? Like where does it says to actually create a table? if I just add that value it will automatically do it? And how does the code knows which table I want it to create? Where does it associates that it should create the TODO table? – Daiane Oct 01 '15 at 12:16
  • 1
    SQL is used, but you can't see the actual command unless you enable tracing. The server is doing it for you when the app is first accessed. I think it knows what tables to create based on the @Table annotation in the TODO class. – opiethehokie Oct 01 '15 at 14:03