Reputation: 155
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;
}
}
Upvotes: 1
Views: 3183
Reputation: 405
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.
Upvotes: 1
Reputation: 1902
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/
Upvotes: 1