0

I have a problem displaying some JPA entities using in Java. I'm not really familiar with the language, so not sure if I can combine the things I have done now. I have this Student class, which obviously represents a student:

@Entity
@Table
public class Student implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;

    @Email
    private String email;

    @Column(unique=true)
    private String studentNumber;

    private String firstName;

    private String lastName;

    public Student() {}

    public Student(String studentNumber, String firstName, String lastName, String email) {
        this.studentNumber = studentNumber;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

Now the idea is to have a RESTFul service and be able to display all students, or just ones by finding their student number. I therefore have this in my persistence class:

@Override
public Student findByStudentNumber(String studentNumber) {
    Object entity = em.createQuery("SELECT * FROM students st where st.studentNumber = :val")
            .setParameter("val", studentNumber).getSingleResult();
    return (Student) entity;
}

@Override
public List<Student> getAll() {
    List<Student> students = em.createQuery(criteriaQuery).getResultList();
    return students;
}

My controller:

@Path("/students")
public class StudentController {
    @Inject
    private StudentPersistence studentPersistence;

@GET
@Path("/get")
public List<Student> getAll() {
    List<Student> all = studentPersistence.getAll();
    return all;
}

@GET
@Path("{studentNr}")
public Student getStudent(@PathParam("studentNr") String id) {
    return studentPersistence.findByStudentNumber(id);
}

But, I cannot seem to get them into the controller, as it keeps throwing 500 Internal server errors. My question: is this the way to combine this, or is there a better way to display these entities?

EDIT: A stacktrace for my 500 error:

01-Aug-2017 14:04:24.769 SEVERE [http-nio-8081-exec-1] com.sun.jersey.spi.container.ContainerResponse.logException Mapped exception to response: 500 (Internal Server Error)
 javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class models.Student, and Java type class models.Student, and MIME media type application/xml was not found
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1479)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at filters.CorsFilter.doFilter(CorsFilter.java:33)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class models.Student, and Java type class models.Student, and MIME media type application/xml was not found
    ... 33 more
dnsko
  • 1,017
  • 4
  • 17
  • 29
  • 500 Internal server error means something wrong with your code. Please add the full stacktrace – StanislavL Aug 01 '17 at 12:03
  • @StanislavL I see, have it there now! – dnsko Aug 01 '17 at 12:05
  • @dnsko, judging by your exception, what you're missing is code responsible for converting `Student` java object into `XML` form. – M. Prokhorov Aug 01 '17 at 12:08
  • It cannot convert Student to xml. Show how you configured the logic. – StanislavL Aug 01 '17 at 12:08
  • @StanislavL That was not the idea either, I was under the assumption I could just fetch the objects in the controller and pass them on to a template or anything. Or even in JSON format is necessary – dnsko Aug 01 '17 at 12:10
  • Add @ResponseBody annotation to your controller methods and add jackson mapper to your libs if you need JSOn. Check http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/ – StanislavL Aug 01 '17 at 12:13
  • Why would you put SQL into "createQuery" ? JPA takes JPQL. JPQL != SQL. Read basic JPA documentation – Neil Stockton Aug 01 '17 at 12:35

3 Answers3

0

500 means internal server error, it seems an unexpected exception was thrown and I could see why, you need to specify the strategy for your generated value, I believe you aim for auto increment so you can use AUTO

@Entity
@Table
public class Student implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

check this link for more info about the strategies you can use

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43
0

So far you have done NOTHING that can display the users' data.. you created a model class(Student) you implemented the CRUD methods(they should be defined using the DAO pattern), you implemented the controllers, but where is the html/jsp that should display the data? I suggest you to use spring to define the web services, it's easyier and better; also you should think of a service layer that calls the DAO layer, then the controller call the service. this way you call the CRUD methods directly from the controller so you connect the web layer to the integration(db) layer: that's wrong.

Implement a jsp or an html file where uìyou display something. Use the jsp tags or something newer(spring) to display the data you want, then have a look at the Service layer, the DAO pattern(but I think you already know it) and spring(the modules you need are the Ioc, dependencies and mvc).

UPDATE: I saw your stacktrace.. I don't know if it's the same problem, have a look at this: A message body writer for Java class not found

Fausto
  • 183
  • 12
0

some modification must be added :

1 - you must specify the table name @Table(name = "table_name")

2 - You must specify the column name, for exemple:

   @Column(name="firstName")
   private String firstName;

3 - When you use HQL, you must specify the entity name and NOT the table name. in you case "SELECT * FROM students.... will be changed by "SELECT * FROM Student.

  • Specifying name in the `@Table` annotation is not mandatory. By default it takes the underscore seperated lowercase class name. And the same goes for `@Column` – Abdullah Khan Aug 01 '17 at 13:05