How to do you insert an object array into a database by using JDBCTemplate
? I have an object array of variable length coming in from my POST
method in my controller.
I have looked at these,
http://www.java2s.com/Tutorial/Java/0417__Spring/PassParameterAsObjectArray.htm
How to insert Integer array into postgresql table using jdbcTemplate in Java Springboot?
As well as others and they do not seem to fit to what I need.
Controller
// Service
@Autowired
private DBService tool;
@PostMapping(value = "/foo")
private void storeData(@RequestBody CustomObject[] customObjects) {
// Calls service then DAO
tool.storeData(customObjects);
}
POJO Object
public class CustomObject {
private Integer id;
private String name;
// Getters & Setters for class attributes
...
}
DAO Is this right? Because I want to store each array element separately, with each element having its own row.
@Autowired
private JdbcTemplate temp;
public void storeData(CustomObject[] customObjects) {
String sql = "INSERT INTO FooBar(name) VALUES(\'" + customObjects.toString() + "\');";
temp.update(sql);
}
Expected
I want to store the array of my custom object from POST
into my database with each element having its own row.
Ideally you would want to iterate over the array and save each "CustomObject" .
private JdbcTemplate temp;
public void storeData(CustomObject customObject) {
String sql = "INSERT INTO FooBar VALUES(" + customObject.id + ",\'"+ customObject.name +"\');";
temp.update(sql);
}
@PostMapping(value = "/foo")
private void storeData(@RequestBody CustomObject[] customObjects) {
// Save each record individually
customObjects.forEach { customObject ->
tool.storeData(customObjects);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.