My code is not reading from DB | Spring Boot, Hibernate, MicroServices and Cloud Forum
A
Abdulmajeed Alroumi Posted on 15/04/2020

So I have build a simple code and wanted it to read from DB but it did not work. It shows in postman error such as below: 
{

    "timestamp": 1586796140242,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/student/"
}
 
And this is my controller: 

package com.mainClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {

    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/student")
    public List<Student> index ()
    {
        return studentRepository.findAll();
    }

    @GetMapping("/student/{id}")
    public Student show (@PathVariable String id)
    {
        int studentId = Integer.parseInt(id);
        return studentRepository.findOne(studentId);
    }

Here is my repository: 

package com.mainClass;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;


public interface StudentRepository extends JpaRepository<Student, Integer> {
    List<Student> findByTitleContainingOrContentContaining (String text, String textAgain);

}

 

 

 

 

 

 

 

Here is my mainApplication: 

package com.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}


My entity: 

package com.mainClass;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)

    private int id;
    private String studentName;
    private String passportNumber;


    public Student ()
    {}

    public Student(int id, String studentName, String passportNumber)
    {
        this.setId(id);
        this.setName(studentName);
        this.setPassportNumber(passportNumber);
    }

    public Student(String studentName, String passportNumber)
    {
        this.setName(studentName);
        this.setPassportNumber(passportNumber);
    }


public int getId()
{
    return id;
}

public void setId(int id)
{
    this.id = id;
}
public String getName (){
        return studentName;
}

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

public String getPassportNumber()
{
    return passportNumber;
}

public void setPassportNumber( String passportNumber)
{
    this.passportNumber = passportNumber;
}

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + id +
                ", name='" + studentName + '\'' +
                ", passport Number='" + passportNumber + '\'' +
                '}';

    }
}

Y
Yogesh Chawla Replied on 15/04/2020

Hi Abdul,

Do you have Student table in database. Make sure your application.properties has correct configuration to connect with mysql database if you have one.

In case you don't have database set then you can also create temporary tables via your code using data.sql and schema.sql in resources folder.

 

As of now, I will suggest you to have database ready with properly created Student table with records in place then you can try the latter.

 

And what is the URL you are trying to run as part of POSTMAN - GET request?

 

This all will help us understand where it is failing. 

404 is just the HTTP response code. On top of that, you can also provide a response body and/or other headers with a more meaningful error message that developers will see which is also explained as part of videos.


A
Abdulmajeed Alroumi Replied on 16/04/2020

Hi Yogesh, 

Thank you very much for reply. 

I do have database set up in my application properties. However, do I need to set up to a new schema to work ? I have the table set up 

This is the URL I am using in POSTMAN: 

http://localhost:8080/student/

 

 

 

My database.sql file: 

CREATE DATABASE restServiceStud;
USE restServiceStud;
CREATE TABLE studentPass (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  studentName VARCHAR(500) NOT NULL,
  passportNumber VARCHAR(5000) NOT NULL
);

 

this is my application.properties: 

spring.datasource.url=jdbc:mysql://localhost:3306/restServiceStud
spring.datasource.username=root
spring.datasource.password=


Y
Yogesh Chawla Replied on 17/04/2020

You are not able to retrieve the data because you have created the table with the name 'studentPass' and the model class with the name 'Student'. That is a mismatch.

Make these names same.

 

Read this. Will help you. 

 

javax.persistence.Entity: Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.

import javax.persistence.Entity;

@Entity
public class Employee implements Serializable {
}

@Table: It specifies the table in the database with which this entity is mapped. In the example below the data will be stores in the “employee” table. Name attribute of @Table annotation is used to specify the table name.

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
}

@Column: Specify the column mapping using @Column annotation.
Name attribute of this annotation is used for specifying the table’s column name.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee implements Serializable {

@Column(name = "employee_name")
private String employeeName;
}

@Id: This annotation specifies the primary key of the entity.

import javax.persistence.*;

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
private int id;
}

@GeneratedValue: This annotation specifies the generation strategies for the values of primary keys.

import javax.persistence.*;

@Entity
@Table(name = "employee")
public class Employee implements Serializable {

@Id
@Column(name = "id")
@GeneratedValue(strategy=SEQUENCE, generator="ID_SEQ")
private int id;
}

 

Now reads this also.

 

@Entity annotation defines that a class can be mapped to a table. And that is it, it is just a marker, like for example Serializable interface.

And why @Entity annotation is mandatory? ... well, it is the way how JPA is designed. When you create a new entity you have to do at least two things

annotated it with @Entity

create an id field and annotate it with @Id

Anything else is optional, for example table name is derived from entity class name (and therefore @Table annotation can be optional), table's columns are derived from entities variables (and therefore @Column annotation can be optional), and so on ...

JPA is trying to provide a fast and easy start to developers who want to learn/use this API, and giving developers option to configure as few things as possible to make something functional is one of the ways how this API wants to achieve this "easy to use/learn" goal. Hence the @Entity annotation (together with @Id annotation) is the minimum you have to do in order to create an entity.

 

Let me know if this helps and your code works after that else we will correct and run the same for you.