How to update a single field using jpa repository using #patch - java

I am developing a simple application by spring boot. I need to restrict the user to be able to only update the name, not all the filed that related to user data but unfortunately, my code has a problem that if someone sends a data in Json format and changes the age or any other field it will be updated but as I told I need the user to be able to change the only name not any other field. I have to mention I am using JPA repository and spring data
my controller
#RestController
#RequestMapping("/student")
public class StudentController {
#Autowired
StudentRepository repository;
// method i user to only update the name field
#PatchMapping("/pattt/{id}")
public ResponseEntity partialUpdateName(
#RequestBody Student partialUpdate,
#PathVariable("id") String id
){
Student.save(partialUpdate, id);
return ResponseEntity.ok(repository.save(partialUpdate));
};
}
JPA repository
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {}
Student class
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue
private int id;
private String name;
private int age;
private String emailAddress;
public Student() { }
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public Student(int id, String name, int age, String emailAddress) {
this.id = id;
this.name = name;
this.age = age;
this.emailAddress = emailAddress;
}
public static void save(Student partialUpdate, String id) {
partialUpdate.setName(id);
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmailAddress() {
return emailAddress;
}
}

The best solution for the future is to add a DTO layer to your application and use it to map to your object. See example below.
public class StudentDto {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then you can map this to your model by Mapstruct:
#Mapper
public abstract class StudentMapper {
public static final StudentMapper INSTANCE =
Mappers.getMapper(StudentMapper.class);
#Mapping
Student studentDtoToStudent(StudentDto studentDto);
}
Mapstruct dependencies:
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</dependency>
You will be able to hide your internal structure from outside world.
In your conroller:
public ResponseEntity partialUpdateName(
#RequestBody StudentDto partialUpdate,
#PathVariable("id") String id)
{
Student student =
StudentMapper.INSTANCE.studentDtoToStudent(partialUpdate);
}
The last line will give you a safe student model which you can then save
Quick solution
In your controller:
public ResponseEntity partialUpdateName(
#RequestBody Student partialUpdate,
#PathVariable("id") String id)
{
Optional<Student> optionalStudent = repository.findById(id);
if(optionalStudent.isPresent() && partialUpdate!=null) {
Student current=optional.get();
current.setName(partialUpdate.getName());
return ResponseEntity.ok(repository.save(current));
}
/* return an error */
}

Related

JSON deserializer returns "null" for Collection type in REST api #RequestBody

I Have a rest controller that is not de-serializing the array type in json..
#PostMapping()
#ResponseBody
public ResponseEntity<Team> createteam(#RequestBody Team team) throws JsonProcessingException {
Team savedTeam = teamService.createTeam(team);
return new ResponseEntity<Team>(savedTeam, HttpStatus.CREATED);
}
below is my entity class.
#Entity
#JsonIdentityInfo(generator = IntSequenceGenerator.class)
public class Team {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "team", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Developer> developers;
public Team(String name, List<Developer> developer) {
super();
this.name = name;
this.developers = developer;
}
public Team() {
super();
}
public List<Developer> getDeveloper() {
return developers;
}
public void setDeveloper(List<Developer> developer) {
this.developers = developer;
}
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;
}
}
and my other entity..
package com.demo.springbootdemo.entity;
#Entity
#JsonIdentityInfo(generator = IntSequenceGenerator.class)
public class Developer {
#Id
#GeneratedValue
private Long id;
#ManyToOne
private Team team;
private Long phone;
private String name;
public Developer() {
super();
}
public Developer(Team team, Long phone, String name) {
super();
this.team = team;
this.phone = phone;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
below is my JSON payload, which returns null "developers" when i call the post method.i have tried changing the number of properties in json payload but, still i am not able to figure out why my json is not de-serilaized to List of developers..
{
"id": 1004,
"name": "claim",
"developers": [
{
"id" :1,
"phone": 9092123,
"name": "raina"
}
]
}
I am not sure what Deserializer are you using, but with the Jackson ObjectMapper I solved it changing the method names of the getter and setter for the developers properties: they should be called setDevelopers and getDevelopers. In your code they are called setDeveloper and getDeveloper, without the final S.
To avoid problem like these, I just add Lombok as a dependency and it takes care of creating setters and getters.
With Lombok your Team class would look like this:
// ... more imports here...
import lombok.Data;
#Data
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public class Team {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "team", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Developer> developers;
}
You may need to add more Lombok annotations for generating constructor methods according to your needs.

Spring Boot Hibernate CRUD REST API 404 Error

I am simply trying to create a Spring boot Hibernate CRUD REST API through this code:
EmployeController.java
#RestController
#RequestMapping("/api")
public class EmployeController {
#Autowired
private EmployeService employeService;
#GetMapping("/employe")
public List<Employe> get(){
return employeService.get();
}
}
Employe.java
#Entity
#Table(name="employe")
public class Employe {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private int id;
#Column
private String name;
#Column
private String gender;
#Column
private String department;
#Column
private Date dob;
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
#Override
public String toString() {
return "Employe [id=" + id + ", name=" + name + ", gender=" + gender + ", department=" + department + ", dob="
+ dob + "]";
}
}
EmployeService.java
public interface EmployeService {
List<Employe> get();
Employe get(int id);
void save(Employe employe);
void delete(int id);
}
EmployeServiceImplement.java
#Service
public class EmployeServiceImplement implements EmployeService {
#Autowired
private EmployeDAO employeDAO;
#Transactional
#Override
public List<Employe> get() {
return employeDAO.get();
}
}
EmployeDAO.java
public interface EmployeDAO {
List<Employe> get();
Employe get(int id);
void save(Employe employe);
void delete(int id);
}
EmployeDAOImplement.java
#Repository
public class EmployeDAOImplement implements EmployeDAO {
#Autowired
private EntityManager entityManager;
#Override
public List<Employe> get() {
Session currentSession = entityManager.unwrap(Session.class);
Query<Employe> query = currentSession.createQuery("from Employe", Employe.class);
List<Employe>list = query.getResultList();
return list;
}
}
I have write all the configuration related to MySQl database into the application.properties and when i run this project as Spring Boot App and go to the Postman and tried like this
and i a unable to understan why it always throws 404 error every time , can anyone tell me what i am missing in this code.
Try with this GET request, it may help you:
http://localhost:8080/api
I checked your code.
where is #RestController for your Controller file and where is #RequestMapping For your method in Controller class?
maybe you should write something like this according to your need.
tell me if you need more help.
#RestController
#RequestMapping("/api")
public class EmployeController {
#RequestMapping(value = "/employ")
public void employ() {
}
}
Instead of this -
#Override
public List get()
Use this -
#RequestMapping(value = "/Employe", method = RequestMethod.GET)
public List get()

#MapKeyColumn in hibernate default value error

I am trying to implement the below example for #MapKeyColumn. There is a OnetoMany relationship between the Company and Persons. However I am getting the below error when I try to persist the Person instance since that is the owner of the relationship:
Caused by: java.sql.SQLException: Field 'name_emp' doesn't have a default value
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:975)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1114)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1062)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1383)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1047)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 20 more
Person Entity
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
int id;
String name;
#ManyToOne(cascade=CascadeType.PERSIST)
//#JoinColumn(name="company_id")
Company company;
public Person()
{}
public Person(String name) {
super();
this.name = 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 Company getcompany() {
return company;
}
public void setcompany(Company c) {
this.company = c;
}
}
Company Entity
#Entity
public class Company {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
int id;
String name;
#OneToMany(cascade=CascadeType.PERSIST,mappedBy="company")
#MapKeyColumn(name="name_emp")
Map<String,Person> persons= new HashMap<>();
public Company()
{}
public Company(String name) {
super();
this.name = name;
}
public Map<String,Person> getPersons() {
return persons;
}
public void setPersons(Map<String,Person> persons) {
this.persons = persons;
}
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;
}
}
MainTest
Person p1 = new Person("jack");
Company c= new Company("ABCORP");
p1.setcompany(c);
session.persist(p1);
The problem might occur because the relationship is not set in the company instance.
Could you try to add the person to the company ether by calling c.getPersons().add(p1.getName(), p1) or by changing the setcompany(...) method to
public void setcompany(Company c) {
c.getPersons().add(this.getName(), this)
this.company = c;
}

How to append multiple records in MySQL Database with crudRepository using Spring-data-JPA?

I am using POST method to insert new records one by one but I am looking forward to push multiple records at a time. My code for single insert is as follows:
#RequestMapping(path="/users")
public class MainController {
#Autowired
private UserRepository userRepository;
#PostMapping(path="/add", consumes="application/json", produces = "application/json")
#Transactional(propagation=Propagation.REQUIRED)
public #ResponseBody String addNewUser(#RequestBody UserFormDto userForm) {
User n = new User();
n.setName(userForm.getName());
n.setEmail(userForm.getEmail());
userRepository.save(n);
return "\n\t\t Saved";
}
}
Entity Class is as follow: Any help will be much appriciatted
package hello;
import javax.persistence.*;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Email;
#SuppressWarnings("unused")
#Entity
public class User {
private String name;
private String email;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
public User() {
}
public User(String email,String name) {
super();
this.name = name;
this.email = email;
}
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;
}
}
You need batch insert update. Check this Spring Data JPA performnace issue with batch save
and this
https://frightanic.com/software-development/jpa-batch-inserts/
Spring curdRepository provides the method
<S extends T> Iterable<S> save(Iterable<S> entities);
using this method you can put the user objects in collection and than save collection object,i hope these help
example:
List<Student> list= new ArrayList<Student>();
for(int i=0;i<3;i++)
{
Student student = new Student();
student.setName("asd");
student.setPercentage(66.66);
student.setTotal(200);
list.add(student);
}
//Saves the list of Student Object
repository.save(list);
}
put all your Objects in a list and then use save() of curdRepository to bulk save.

Spring Data JPA ManyToOne Bidirectional

Problem: it works till i try to add Student obejcts to Database, but the tables are being created correctly .
I can't simplify the post any further. But it's mainly code that doesn't require a lot of reading, it's a simple spring data repository service model. I posted it all due to the fact idk what am i doing wrong. Problem is in the JPA mapping.
I got the example from over here http://www.java2s.com/Tutorial/Java/0355__JPA/OneToManyBidirectional.htm
MDOELS
#Entity
public class Department {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#OneToMany(mappedBy="department")
private Collection<Student> students;
public Department() {
}
public Department(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String deptName) {
this.name = deptName;
}
public Collection<Student> getStudents() {
return students;
}
public void setStudent(Collection<Student> students) {
this.students = students;
}
public String toString() {
return "Department id: " + getId() +
", name: " + getName();
}
}
#Entity
public class Student {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#ManyToOne (cascade=CascadeType.ALL)
private Department department;
public Student() {
}
public Student(String name, Department department) {
this.name = name;
this.department = department;
}
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 Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String toString() {
return "\n\nID:" + id + "\nName:" + name + "\n\n" + department;
}
}
REPOSITORIES
#Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer> {
Department findByName(String name);
}
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
Student findByName(String name);
}
SERVICES
#Service
public class StudentService {
private final StudentRepository studentRepository;
#Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public void addToDatabase(Student student) {
this.studentRepository.saveAndFlush(student);
}
public Student getStudentByName(String name) {
return studentRepository.findByName(name);
}
}
#Service
public class DepartmentService {
private final DepartmentRepository departmentRepository;
#Autowired
public DepartmentService(DepartmentRepository departmentRepository) {
this.departmentRepository = departmentRepository;
}
public void addToDataBase(List<Department> department) {
this.departmentRepository.save(department);
department.forEach(this.departmentRepository::saveAndFlush);
}
public Department getDepartmentByName(String name){
return this.departmentRepository.findByName(name);
}
}
My main method
#Component
public class Terminal implements CommandLineRunner {
private final StudentService studentService;
private final DepartmentService departmentService;
#Autowired
public Terminal(StudentService studentService, DepartmentService departmentService) {
this.studentService = studentService;
this.departmentService = departmentService;
}
#Override
public void run(String... strings) throws Exception {
Department department = new Department("dep1");
Department department1 = new Department("dep2");
Department department2 = new Department("dep3");
Department department3 = new Department("dep4");
List<Department> departments = new ArrayList<>(Arrays.asList(department, department1, department2, department3));
this.departmentService.addToDataBase(departments);
//
Student student = new Student("pesho", department);
Student student11 = new Student("gosho", department1);
this.studentService.addToDatabase(student11);
this.studentService.addToDatabase(student);
student = new Student("sasho", department2);
this.studentService.addToDatabase(student);
// System.out.println(this.studentService.getStudentByName("gosho").getDepartment1());
// System.out.println("CHECKING ONE TO ONE BIDIRECTIONAL: " + this.departmentService.getDepartmentByName("dep1").getStudent());
}
}
So here when i try to add students in the students table it gives an error
The error is the fallowing
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: app.models.Department
you added cascade= CascadeType.ALL for Department in Student class and save departments separete. this.departmentService.addToDataBase(departments);
fix : dont call
departmentService.addToDataBase(departments);
or remove CascadeType.ALL from Student
Well I can't understand you problem completely but here's what I would like to add. Cascading for add operation is not implemented or it's incomplete. Hope it helps.

Categories

Resources