#PostMapping And #PutMapping getting null values - json

I have created a simple Spring REST service (POST, PUT). But when i call this service from postman when value store in null.
Student Pojo Class
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.hateoas.ResourceSupport;
#SuppressWarnings("serial")
#Entity
#Table(schema="fishpool")
public class Student extends ResourceSupport implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private Long sId;
private String name;
private String email;
public Student() {
}
public Student(Long sId, String name, String email) {
this.sId = sId;
this.name = name;
this.email = email;
}
public Long getsId() {
return sId;
}
public void setsId(Long sId) {
this.sId = sId;
}
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;
}
#Override
public String toString() {
return "Student [sId=" + sId + ", name=" + name + ", email=" + email + "]";
}
}
RestController Class
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.domain.Student;
import com.example.studentService.StudentSerivce;
#RestController
#RequestMapping(value="/api")
public class StudentController {
#Autowired
private StudentSerivce studentService;
private final static Logger log = LoggerFactory.getLogger(StudentController.class);
public StudentController(final StudentSerivce studentService) {
this.studentService = studentService;
}
#GetMapping("/students")
public List<Student> getAllStudent() {
return studentService.findAllStudent();
}
#GetMapping("/student/{id}")
public Student getStudentById(#PathVariable("id") Long id) {
return studentService.findByStudentId(id);
}
#PostMapping("/createStudent")
public ResponseEntity<Student> createStudent(Student student) {
HttpHeaders headers = new HttpHeaders();
headers.add("Reader", "StudentController");
log.info("Post Create Student : " + student);
return new ResponseEntity<Student>(student, headers, HttpStatus.CREATED);
}
#PutMapping("/updateStudent")
public Student updateStudent(Student student) {
log.info("Put Update Student : " + student);
return studentService.updateStudent(student);
}
#DeleteMapping("/deleteStudent/{id}")
public void deleteStudentById(#PathVariable Long id) {
studentService.deleteByStudentId(id);
}
}
Error.log
2018-07-06 14:31:05.405[0;39m [32m INFO[0;39m [35m20240[0;39m [2m---[0;39m [2m[nio-8080-exec-7][0;39m [36mc.example.controller.StudentController [0;39m [2m:[0;39m Put Update Student : Student [sId=null, name=null, email=null]
[2m2018-07-06 14:31:05.705[0;39m [32mDEBUG[0;39m [35m20240[0;39m [2m---[0;39m [2m[nio-8080-exec-7][0;39m [36morg.hibernate.SQL [0;39m [2m:[0;39m insert into student (email, name) values (?, ?)
Hibernate: insert into student (email, name) values (?, ?)
[2m2018-07-06 14:31:44.984[0;39m [32m INFO[0;39m [35m20240[0;39m [2m---[0;39m [2m[nio-8080-exec-8][0;39m [36mc.example.controller.StudentController [0;39m [2m:[0;39m Post Create Student : Student [sId=null, name=null, email=null]
I have no idea where is my mistake, please find the my mistake and suggest me. Please help me. I totally Confused where is my mistake.

Add #RequestBody annotation before Student student like below.
public ResponseEntity<Student> createStudent(#RequestBody Student student)
mark the fields with #JsonProperty like this
#JsonProperty String sId;
#JsonProperty String name;
etc.

I am facing the same problem. the reason why I got the null value because of bad JSON request.
I make a mistake:
{
"name": "111",
"id":"11""
}
after delete the suplus semicolon, the problem fixed.

As Alien pointed out there should be a #RequestBody annotation attached to the model parameter of the post method.
#PostMapping("/createStudent")
public ResponseEntity<Student> createStudent(#RequestBody Student student) {
HttpHeaders headers = new HttpHeaders();
headers.add("Reader", "StudentController");
log.info("Post Create Student : " + student);
return new ResponseEntity<Student>(student, headers, HttpStatus.CREATED);
}
Also, I would suggest that you remove the
#SuppressWarnings("serial") & #Table(schema="fishpool")
Annotations as only the #Entity Annotation is needed with (with the getters and setters of the Model)

Related

java.sql.SQLIntegrityConstraintViolationException: Post method is not working for one to many mapping in Spring Boot

I use the technologies jpa, hibernate, spring boot - data, api REST, MySql
Please help me out regarding this ERROR..!
Hibernate: select creditcard0_.credit_id as credit_i1_2_0_, creditcard0_.cardno as cardno2_2_0_, creditcard0_.creditname as creditna3_2_0_, creditcard0_.cvv as cvv4_2_0_, creditcard0_.uid as uid5_2_0_ from credit_card creditcard0_ where creditcard0_.credit_id=? Hibernate: insert into credit_card (cardno, creditname, cvv, uid, credit_id) values (?, ?, ?, ?, ?) 2022-12-22 11:39:10.208 WARN 2368 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000 2022-12-22 11:39:10.208 ERROR 2368 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'uid' cannot be null 2022-12-22 11:39:10.209 INFO 2368 --- [nio-8080-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2022-12-22 11:39:10.223 ERROR 2368 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'uid' cannot be null at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061) ~[mysql-connector-j-8.0.31.jar:8.0.31]
Here is my code:
**User.java**
import java.io.Serializable; import java.util.Set;
import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.transaction.Transactional;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
#Transactional #Entity #Table(name="users") public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO,generator="native")
#GenericGenerator(name = "native",strategy = "native")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="phoneno")
private int phone_no;
#Column(name="address")
private String address;
private String pwd;
#OneToMany(mappedBy = "user",fetch=FetchType.LAZY,cascade = CascadeType.ALL)
private Set<CreditCard> creditcard;
public User() {
}
public User(String name, String email, int phone_no, String address, String pwd) {
super();
this.name = name;
this.email = email;
this.phone_no = phone_no;
this.address = address;
this.pwd=pwd;
}
public Set<CreditCard> getCreditcard() {
return creditcard;
}
public void setCreditcard(Set<CreditCard> creditcard) {
this.creditcard = creditcard;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail_id(String email) {
this.email = email;
}
public int getPhone_no() {
return phone_no;
}
public void setPhone_no(int phone_no) {
this.phone_no = phone_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
#Override
public String toString() {
return "User [uid=" + id + ", name=" + name + ", email=" + email + ", phone_no=" + phone_no
+ ", address=" + address + ", pwd=" + pwd + "]";
}
}
**CreditCard.java**
import java.io.Serializable;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.transaction.Transactional;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Transactional
#Entity
#Table(name="credit_card")
public class CreditCard implements Serializable {
#Id
private int credit_id;
private String cardno;
private String cvv;
private String creditname;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne(fetch=FetchType.LAZY,optional = true)
#JoinColumn(name="uid",nullable = true)
private User user;
public CreditCard() {
super();
// TODO Auto-generated constructor stub
}
public CreditCard( String cardno, String cvv, String creditname,User user) {
super();
//this.credit_id = credit_id;
this.cardno = cardno;
this.cvv = cvv;
this.creditname = creditname;
this.user=user;
}
public int getCredit_id() {
return credit_id;
}
public void setCredit_id(int credit_id) {
this.credit_id = credit_id;
}
public String getCardno() {
return cardno;
}
public void setCardno(String cardno) {
this.cardno = cardno;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getCreditname() {
return creditname;
}
public void setCreditname(String creditname) {
this.creditname = creditname;
}
#JsonIgnore
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "CreditCard [credit_id=" + credit_id + ", cardno=" + cardno + ", cvv=" + cvv + ", creditname="
+ creditname + "]";
}
}
**UserController.java**
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.Grocery.Grocery.model.User;
import com.Grocery.Grocery.repository.GroceryRepository;
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private GroceryRepository groceryRepository;
#GetMapping
public List<User> getAllUsers()
{
return groceryRepository.findAll();
}
#GetMapping("/{id}")
public ResponseEntity getbyid(#PathVariable("id") int id) {
return new ResponseEntity(groceryRepository.findById(id), HttpStatus.OK);
}
}
**CreditCardController.java**
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.Grocery.Grocery.model.CreditCard;
import com.Grocery.Grocery.repository.CreditCardRepository;
#RestController
#RequestMapping("/creditcard")
public class CreditCardController {
#Autowired
private CreditCardRepository creditcardRepository;
#GetMapping
public List<CreditCard> getAllCreditCard(){
return creditcardRepository.findAll();
}
#PostMapping("/add")
#ResponseBody
public CreditCard createEmployee(#RequestBody CreditCard credit) {
return creditcardRepository.save(credit);
}
}
**GroceryRepository.java(UserRepository.java)**
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.Grocery.Grocery.model.User;
#Repository
public interface GroceryRepository extends JpaRepository<User, Integer> {
List<User> findByEmail(String email);
}
**CreditCardRepository.java**
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.Grocery.Grocery.model.CreditCard;
#Repository
public interface CreditCardRepository extends JpaRepository<CreditCard, Integer>{
}
aaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaf awe fffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeee eeeeeeeeeeeeeeeeeeeeee eeeggg gggg gggggggggggggggggg kkkkkkkkkkkkkkkkkkk

SpringBoot #OneToMany Postman Request not working

1.User Class with OneToMany Annotation in relation to Roles class that can be many
2.Roles Class with #ManyToOne and #JoinColumn Annotation
3.Controller class with the endpoint
4.Postman request with Json Object throws an Exception, JSON parse error: Cannot deserialize instance of com.cvt.programmingTask.model.User out of START_ARRAY token
Class User()
package com.cvt.programmingTask.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email_id", unique=true)
private String emailId;
#OneToMany(mappedBy = "user")
private Set<Roles> roles;
public User() {
}
public User(String firstName, String lastName, String emailId, Set<Roles> roles) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.roles = roles;
}
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 getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Set<Roles> getRoles() {
return roles;
}
public void setRoles(Set<Roles> roles) {
this.roles = roles;
}
}
Class Roles :
package com.cvt.programmingTask.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="roles")
public class Roles {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "name")
private String name;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="user_id", nullable=false)
private User user;
public Roles() {
}
public Roles(Long id, String name, User user) {
super();
this.id = id;
this.name = name;
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Controller Java File
package com.cvt.programmingTask.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cvt.programmingTask.exception.ResourceNotFoundException;
import com.cvt.programmingTask.model.User;
import com.cvt.programmingTask.repository.UserRepository;
/**
* #author edibi
*
*/
//#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/api/v1")
public class UserController {
#Autowired
private UserRepository userRepository;
//get all users
#GetMapping("/users")
public List<User> getAllUsers(){
return userRepository.findAll();
}
//create user rest api
#PostMapping("/users")
public User createUser(#RequestBody User user) {
return userRepository.save(user);
}
//get user
#GetMapping ("/users/{id}")
public ResponseEntity<User> getUserById(#PathVariable Long id) {
User user = userRepository.findById(id)
.orElseThrow(()->new ResourceNotFoundException("User does not exist with id : " +id));
return ResponseEntity.ok(user);
}
//update user
#PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(#PathVariable Long id, #RequestBody User userDetails){
User user = userRepository.findById(id)
.orElseThrow(()->new ResourceNotFoundException("User does not exist with id : " +id));
user.setFirstName(userDetails.getFirstName());
user.setLastName(userDetails.getLastName());
user.setEmailId(userDetails.getEmailId());
user.setRoles(userDetails.getRoles());
User updatedUser = userRepository.save(user);
return ResponseEntity.ok(updatedUser);
}
//delete User rest api
#DeleteMapping("/users/{id}")
public ResponseEntity< Map<String, Boolean> >deleteUser(#PathVariable Long id){
User user = userRepository.findById(id)
.orElseThrow(()->new ResourceNotFoundException("User does not exist with id : " +id));
userRepository.delete(user);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return ResponseEntity.ok(response);
}
}
Can you help me out really don't know what'S wrong. Thanks

What are the steps required to create spring boot project using database first approach? Database used here is MySQL

I am learning spring boot (for REST API). I have read spring boot documentation and other tutorials but all are based on creating database tables using entities (code first approach). One of the tutorials talked about JBoss(installed in from Eclipse marketplace). So I followed the tutorial and I was able to create entities, dao, pojo classes from database tables. But the tutorial doesn't talk about how to perform crud operations now. So I tried to perform some crud operation and I am getting errors.
UserController
package com.example.dbfirst.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.dbfirst.entities.User;
import com.example.dbfirst.service.UserService;
#RestController
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("users/{id}")
public User getUser(#PathVariable("id") int id) {
return this.userService.getUser(id);
}
}
UserService
package com.example.dbfirst.service;
import javax.ejb.EJB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dbfirst.dao.UserHome;
import com.example.dbfirst.entities.User;
#Service
public class UserService {
//#Autowired
private UserHome userHome;
public User getUser(int id) {
userHome=new UserHome();
return this.userHome.findById(id);
}
}
User DAO class using JBoss and hibernate.cfg.xml
UserHome
package com.example.dbfirst.dao;
// Generated 25-Mar-2021, 4:50:30 pm by Hibernate Tools 5.2.12.Final
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import com.example.dbfirst.entities.User;
#Stateless
public class UserHome {
private static final Log log = LogFactory.getLog(UserHome.class);
#PersistenceContext
private EntityManager entityManager;
public void persist(User transientInstance) {
log.debug("persisting User instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void remove(User persistentInstance) {
log.debug("removing User instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public User findById(Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = entityManager.find(User.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
UserEntities
package com.example.dbfirst.entities;
// Generated 25-Mar-2021, 4:12:53 pm by Hibernate Tools 5.2.12.Final
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* User generated by hbm2java
*/
#Entity
#Table(name = "user", catalog = "mydb")
public class User implements java.io.Serializable {
private Integer id;
private String email;
private String password;
public User() {
}
public User(String email, String password) {
this.email = email;
this.password = password;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "email", length = 45)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "password", length = 45)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
User Pojo class
package com.example.dbfirst.pojo;
// Generated 25-Mar-2021, 4:09:56 pm by Hibernate Tools 5.2.12.Final
/**
* User generated by hbm2java
*/
public class User implements java.io.Serializable {
private Integer id;
private String email;
private String password;
public User() {
}
public User(String email, String password) {
this.email = email;
this.password = password;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
Now When I call "users/id" from POSTMAN, I am getting this error:
"status": 500,
"error": "Internal Server Error",
"message": "Cannot invoke \"javax.persistence.EntityManager.find(java.lang.Class, Object)\" because \"this.entityManager\" is null",
"path": "/users/2"
I might be missing some steps or I might have made some mistake somewhere.
It would be helpful if you can tell me the steps required to create spring boot project using database first approach (upto crud operation). You can also share some articles/link.
I have already looked at many articles to solve this issue. The reason I want database first approach are following:
I want to keep database part separate from spring project coding part (Don't want to mix them at such level)
I want to design database separately , completely independent of project type.
Thank you for your help.
In your case follow these steps:
Create your database table first.
Turn off auto-create and auto-update.
There is lot of unnecessary lines in your code.
Create only Entity class(add dto later)
Directly access repository from controller(remove service layer for now add later )
If have map columns to entity field properly other-wise it will cause errors(Use #Cloumn(name ="name")) for avoiding error and Use #Id for primary key.
You can refer:
Disable auto update in spring data jpa
https://spring.io/guides/gs/accessing-data-jpa/

How to store java objects in mysql using jpa?

I have converted the JSON into POJO using GSON.
I am looking to store Employee entity object into mysql using JPA's save() method. But I am getting an error saying "cannot determine the type for Address". So how should I go with this?
Here is the error:
Could not determine type for : Address
Employee.java
package com.example.demo;
import java.math.BigDecimal;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.google.gson.annotations.Expose;
#Entity
public class Employee {
#Id
private int id;
private String name;
private int age;
private BigDecimal salary;
private String designation;
private Address address;
private long[] phoneNumbers;
/*Getter and Setter Methods*/
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public long[] getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(long[] phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.Id;
//#Entity
public class Address {
#Id
private String street;
private String city;
private int zipCode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getZipCode() {
return zipCode;
}
public void setZipcode(int zipcode) {
this.zipCode = zipcode;
}
#Override
public String toString(){
return getStreet() + ", "+getCity()+", "+getZipCode();
}
}
Controller Class
package com.example.demo;
import net.sf.json.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import net.sf.json.JSONObject;
#Controller // This means that this class is a Controller
#RequestMapping(path="/demo") // This means URL's start with /demo
(after Application path)
public class MainController {
#Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it
to handle the data
private UserRepository userRepository;
#GetMapping(path="/add") // Map ONLY GET Requests
public #ResponseBody String addNewUser (#RequestBody String json) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
//JSONObject jsonObject = JSONObject.fromObject(json);
Gson gson=new GsonBuilder().create();
Employee employee =gson.fromJson(json,Employee.class);
userRepository.save(employee);
return "Successfully added to database using JPA!";
}
#GetMapping(path="/all")
public #ResponseBody Iterable<Employee> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
Try adding implements Serializable for your Entity classes.
ie.
#Entity
public class Employee implements Serializable{
}
Whenever you use #Entity annotation in your class and trying to save its instance in database. At very intially a create table command is formed in hibernate which creates table in the database with the given specifications. As in employee table you specify the datatypes of all data-members. When cursor come to 'Address', it gave error because hibernate not able to find any datatype related this or any table related this.
As you commented #Entity annoatation in Address class. So no table regarding that will be created in database.
Address is class reference for this hibernate need the class(table). As class(table) is not there ,so the error comes.

How to correct sql statement to give correct result

I'm running a local MySQL Server on port 3306 with a schema "sys" featuring a table "users"
Now I have a small spring boot application to query all entries from that table.
Model for that table is:
package com.example.databaseneu.model;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Users {
#Id
// #Column(name = "id")
private int id;
// #Column(name = "name")
private String name;
// #Column(name = "salary")
private int salary;
// #Column(name = "team_name")
private String team_name;
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;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getTeam_name() {
return team_name;
}
public void setTeam_name(String team_name) {
this.team_name = team_name;
}}
The connection works, but the query doesnt seem to deliver the right result as I get the Whitelabel Error Page.
Query to get all elements from the table (autogenerated by repository)
Hibernate:
select
users0_.id as id1_0_,
users0_.name as name2_0_,
users0_.salary as salary3_0_,
users0_.team_name as team_nam4_0_
from
users users0_
So I'm uncertain if i defined the Entity wrong or something else alltogether
#Column Tag doesnt do the trick.
---Edit---
package com.example.databaseneu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.databaseneu.model.Users;
import com.example.databaseneu.repository.UserRepository;
#Controller // This means that this class is a Controller
#RequestMapping(path = "/demo") // This means URL's start with /demo (after Application path)
public class MainController {
#Autowired
private UserRepository userRepository;
#GetMapping(path = "/add")
public #ResponseBody String addNewUser(#RequestParam String name, #RequestParam int salary,
#RequestParam String team_name) {
Users n = new Users();
n.setName(name);
n.setSalary(salary);
n.setTeam_name(team_name);
userRepository.save(n);
return "Saved";
}
#GetMapping(path = "/all")
public Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
So id navigate to localhost:8080/demo/all
You have written all correct expect for one thing. Mark your return-type with #ResponseBody annotation -- similar to your addNewUser method.
#GetMapping(path = "/all")
public #ResponseBody Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
Hopefully this should work. If you still face issues, post it here.