I started learning Spring and been watching this video https://youtu.be/9SGDpanrc8U from
Amigoscode. I followed along and did what he did but my code acts differently than his, maybe i missed something, but I set on it for two hours trying to figure out what's not working and nothing works.
here is the code
package com.example.demo;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.Student.*;
#SpringBootApplication
#RestController
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
#GetMapping
public List<Student> hello() {
return List.of(
new Student(
1L,
"Mariam",
"Marim.jamal#gmail.com",
LocalDate.of(2000, Month.JANUARY, 5),
21
)
);
}
}
And the Student class
package com.example.demo.Student;
import java.time.LocalDate;
public class Student {
private long id;
private String name;
private String email;
private LocalDate dob;
private Integer age;
public Student(Long id, String name, String email, LocalDate dob, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
this.age = age;
}
public Student(String name, String email, LocalDate dob, Integer age) {
this.name = name;
this.email = email;
this.dob = dob;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Student{" +
"id=" + id +
", name='" + name + "'" +
", email='" + email +"'" +
", dob=" + dob +
", age=" + age +
"}";
}
}
when he runs the code in the video, the websites loads a list with a single student details in it.
when I run it, it shows this:
Whitelabel Error Page \n This application has no explicit mapping for /error, so you are seeing this as a fallback
I checked Stack Overflow and other websites for this problem, most say it is because the controller doesn't handle what to do in case of an error, but that's not the case here. and the others say it's because packaging hierarchy, i tried splitting Demo2Application into two, one for the Application one for the RestController and put them in hierarchical order where Demo2Application shows before RestController, still didn't work so I reversed the splitting back to what the video showed.
Here is the log when I run:
Log
Truly Frustrated, will appreciate anything you have for me.
maybe you can assign a value to the annotation GetMapping,like #GetMapping("/query").then by this url http://localhost:8080/query to visit.
Related
I'm new to java reflexion and I'm trying to integrate SQLite with java.
I have 2 objects Person and Department. There is relation OneToMany between them.
As I'm working on save functionality (SQLite) I want to extract field names and its values so I can build full query. I have no problem with extracting names and values of fields that are of primitive type (String, int etc.). I have problem with type of Object (in this case it is Department field in Person object).
I'm able to print object but unable to access its fields (namely pk).
Could you help me please?
METHOD FOR EXTRACTING FIELDS
// method for extracting fields
private StringBuilder getFieldsWithValues(Object entity) throws IllegalAccessException, NoSuchFieldException {
StringBuilder query = new StringBuilder();
for (Field field : entity.getClass().getDeclaredFields()) {
System.out.print((field.getName() + " - "));
field.setAccessible(true);
// TODO: eliminate if statement from for cycle
if (field.isAnnotationPresent(ManyToOne.class)) {
// HERE I want to extract the pk value from Department object
System.out.println(field.get(entity));
} else {
System.out.println(field.get(entity));
}
}
return query;
}
DEPARTMENT OBJECT
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Department {
#Id
private long pk;
private String name;
private String code;
public Department() {
}
public Department(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String toString() {
return String.format("Department %d: %s (%s)", pk, name, code);
}
}
PERSON OBJECT
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Person {
#Id
private long id;
private String surname;
private String name;
private int age;
#ManyToOne
private Department department;
public Person(String surname, String name, int age) {
this.surname = surname;
this.name = name;
this.age = age;
}
public Person() {
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getId() {
return id;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return String.format("Person %d: %s %s (%d)", id, surname, name, age);
}
}
I'm trying to practice REST API with Spring, but I am having an issue where it's saying
No converter found for return value of type: class org.codestrs.resources.Employee
From what I've read, this is mostly caused by there not being a getter methods for a class, Employee in this case. The weird thing is, I do have them in there.
EDIT: Just an FYI, this is a Dynamic Web Project, and I had to build my project without Spring Boot, so I manually added the spring functionality.
package org.codestrs.resources;
import java.util.Objects;
public class Employee {
private Long id;
private String name;
private String role;
Employee() {}
public Employee(Long id, String name, String role) {
this.id = id;
this.name = name;
this.role = role;
}
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getRole() {
return this.role;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setRole(String role) {
this.role = role;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee employee = (Employee) o;
return Objects.equals(this.id,employee.id) && Objects.equals(this.name, employee.name) && Objects.equals(this.role, employee.role);
}
public String toString() {
return "Employee{" + "id=" + this.id + ", name=" + this.name + ", role=" + this.role + " }";
}
}
(And here's my controller for reference)
package org.codestrs.controller;
import org.codestrs.resources.Employee;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class EmployeeController {
#GetMapping("/employees/{id}")
Employee one(#PathVariable Long id) {
Employee emp = new Employee(id,"Nick","Designer");
return emp;
}
}
Looking at these, I'm not sure what the issue is. Any help would be greatly appreciated.
I'm using Spring boot trying to obtain a JSON response with #RestController and #GetMapping and it does not come out with JSON on the local host. This is my code. Can anyone fix this?
#SpringBootApplication
#RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#GetMapping
public List<Employee> hello () {
return List.of(
new Employee(
1L,
"Pedro",
"rt.pedrosantos#gmail.com",
LocalDate.of(1989, Month.JUNE, 21),
32
)
);
}
}
The Following is the "Employee" Class with setters and getters I created to go with it.
package com.example.employee;
import java.time.LocalDate;
public class Employee {
private Long id;
private String name;
private String email;
private LocalDate dob;
private Integer age;
public Employee() {
}
public Employee(Long id,
String name,
String email,
LocalDate dob,
Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
this.age = age;
}
public Employee(String name,
String email,
LocalDate dob,
Integer age) {
this.name = name;
this.email = email;
this.dob = dob;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", dob=" + dob +
", age=" + age +
'}';
}
}
class ends here. I'm not able to properly return the code to JSON and I'm not sure why. Can anyone explain?
Edit: It returns a Json. Check if your browser or rest client is properly configured.
Previous answer:
Refer to this: As you have annotated with #RestController there is no need to do explicit json conversion. Since you're not returning a POJO, and according to the code you've posted you don't have any getters, changing it to the following does the job:
#RequestMapping(value = "hello_world", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<StringResponse> hello() {
return List.of(new StringResponse("Hello"),new StringResponse("World"));
}
}
class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
or use a library like Gson: There is a clean way to return string as json in a Spring Web API?
Example:
#RequestMapping(value = "hello_world", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> hello() {
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<List<String>>() {}.getType();
String json = "[ \"Hello\", \"World\"]";
List<String> responseList = gson.fromJson(json, type);
return responseList;
}
More info: Spring MVC - How to return simple String as JSON in Rest Controller
How to return JSON data from spring Controller using #ResponseBody
Not sure what you're trying to do, but creating a model class with corresponding setters / getters should be the way.
I am working on a Spring Boot project and decided to use MongoDB . I just want to generate sequence number in MongoDB. So even if 100s of different clients trying to do that, I do not want to conflict any generated number. Is there any way to do that ?
Also I tried to make something like this :
SequenceNumber sequenceNumber;
String SEQUENCE_NAME = "example";
sequenceNumber = mongoOperations.findAndModify(query(where("_id").is(SEQUENCE_NAME)),
new Update().inc("number", 1), options().returnNew(true).upsert(true),
SequenceNumber.class);
return sequenceNumber.getNumber();
Is this correct ?
Thanks for answers !
https://www.javaprogramto.com/2019/05/spring-boot-mongodb-auto-generated-field.html
First, create a collection that will store the auto-incremented value in it. This can be created using either the mongo shell or MongoDB Compass
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "database_sequences")
public class DatabaseSequence {
#Id
private String id;
private long seq;
public DatabaseSequence() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getSeq() {
return seq;
}
public void setSeq(long seq) {
this.seq = seq;
}
}
Let’s then create a users_db collection. This collection stores the users that are being used.
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "users_db")
public class User {
#Transient
public static final String SEQUENCE_NAME = "users_sequence";
#Id
private long id;
private String firstName;
private String lastName;
private String email;
public User() { }
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" + "id=" + id + ", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}';
}
I followed the microservices tutorial from youtube to create independent services (spring boot Application)
I created a service implementation java file providing method definitions for the request mapping URL (/catalog/userId) for the read operation
To the above requested URL, returning a list of objects as the response body (HTTP response) for the HTTP read request
In the java, error occurring for the function definition of sending a list of objects
The error occurs in line 17 of MovieCatalogResource.java stating the illegal start of expression, unexpected token
I researched for the error but still I am struck with the execution
can you guys kindly provide your help to resolve issue with your suggestions
Providing the code below
CatalogItem.java
package com.example.moviecatalogservice;
public class CatalogItem {
private String name;
private String desc;
private int rating;
public CatalogItem(String name, String desc, int rating){
this.name = name;
this.desc = desc;
this.rating = rating;
}
public int getRating(){
return rating;
}
public void setRating(){
this.rating = rating;
}
public String getName(){
return name;
}
public void setName(){
this.name = name;
}
public String getDesc(){
return desc;
}
public void setDesc(){
this.desc = desc;
}
}
MovieCatalogService.java
package com.example.moviecatalogservice;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.an notation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
#RestController
#RequestMapping("/catalog")
public class MovieCatalogResource {
#RequestMapping("/{userId}")
//public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
return Collections.singletonList(
new CatalogItem(name: "transformers", desc:"Test", rating:4)
);
}
}
change
new CatalogItem(name: "transformers", desc:"Test", rating:4)
To
new CatalogItem("transformers", "Test", 4)
You must have a matching CatalogItem() constructor in CatalogItem
Entity Or Model
After a change at line no 17 of MovieCatalogResource.java it will look like as below
#RestController
#RequestMapping("/catalog")
public class MovieCatalogResource {
#RequestMapping("/{userId}")
//public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
return Collections.singletonList(
new CatalogItem("transformers", "Test", 4)
);
}
}
Working Example
Controller.java
#GetMapping("/{id}")
public List<User> getUser(#PathVariable(name="id") int id)
{
return Collections.singletonList(
new User(1,"username")
);
}
User.java
public class User {
private int id;
private String name;
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
Tested using Postman
Why are you doing this :
new CatalogItem(name: "transformers", desc:"Test", rating:4)
instead of this :
new CatalogItem("transformers", "Test", 4)
at line no 17 of MovieCatalogResource.java?
Change the below statement from new CatalogItem(name: "transformers", desc:"Test", rating:4) to new CatalogItem("transformers","Test",4)