2017-07-18 20 views
1

我正在使用POST方法逐個插入新記錄,但我期望一次推送多個記錄。我對單個插入代碼如下:如何在使用Spring-data-JPA的crudRepository中追加MySQL數據庫中的多條記錄?

@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"; 
} 
} 

實體類如下:任何幫助將非常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; 
} 
} 
+0

你從哪裏得到多個用戶?你的方法addNewUser()只有一個用戶。 –

+0

可能的重複:https://stackoverflow.com/questions/32793403/crudrepository-and-hibernate-savelists-vs-saveentity-in-transaction –

回答

1

春curdRepository提供了使用這種方法,你可以把用戶對象的集合,比保存集合對象,我希望這些幫助

例如方法

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); 
} 

把所有的對象中一個列表,然後使用curdRepository的save()進行批量保存。

+0

你能解釋一下函數參數嗎? –

+0

檢查我編輯過的答案會給你完整的想法。 –

相關問題