Reputation: 497
I have a list of DTO classes which need to be save into database table. Only last item is being saved into the database due to some unknown reason which I am not able to tracked.
Find below the sample service and manager class,
class TestService {
public void saveData(List<OrderDTO> dtolist) {
//exception handling properly
transaction.begin();
manager.saveAlldata(dtolist);
transaction.commit();
}
}
Class TestManager {
public void saveAlldata(List<OrderDTO> dtolist) {
//exception handles properly
for(OrderDTO dto: dtolist){
OrderPersist persist = new OrderPersistent();
persist.setId(dto.getId());
persist.setItem(dto.getItem());
//save(persist) or merge(persist);
}
}
Assume I have 2 item details e.g. id=1, Item=S_001 and Id=2, Item=S_002 in the dto list then only last item (2, S_002) is being saved into the table.
Upvotes: 1
Views: 642
Reputation: 316
Have u tried this?
public void saveAlldata(List<OrderDTO> dtolist) {
//exception handles properly
for(OrderDTO dto: dtolist){
transaction.begin();
OrderPersist persist = new OrderPersistent();
persist.setId(dto.getId());
persist.setItem(dto.getItem());
//save(persist) or merge(persist);
transaction.commit();
}
}
Upvotes: 1
Reputation: 18968
You need to session.save
inside the for loop.
for(OrderDTO dto: dtolist){
OrderPersist persist = new OrderPersistent();
persist.setId(dto.getId());
persist.setItem(dto.getItem());
session.save(persist);
}
Also consider keeping a count of the save and can use a counter. Something like the following:
if( i % 50 == 0 ) {
session.flush();
session.clear();
}
where i is the count.
Upvotes: 0