0

As given in the below code I am inserting data in table by simple hibernate code. But when all the fields are then also it is saving data in table but only id is changed (auto-incremented). I want to know is there any way to know that the same data exists in table & I can save redundant inserts. Please tell an easy way I know I can write queries anytime to figure out the same.

List<Route> listRoute = newList();
listRoute.get(0).setSource("DelhiTest");
listRoute.get(0).setDestination("KotaTest");
listRoute.get(1).setSource("DelhiTest");
listRoute.get(1).setDestination("KotaTest");
listRoute.get(2).setSource("DelhiTest");
listRoute.get(2).setDestination("KotaTest");
RowReferenceByEntity.setListRoute(listRoute);
new RouteDAOImpl().saveOnly(listRoute.get(0));
new RouteDAOImpl().saveOnly(listRoute.get(1));
new RouteDAOImpl().saveOnly(listRoute.get(2));

Thanks

Amit Kumar
  • 2,685
  • 2
  • 37
  • 72
  • 2
    If `Route` has `equals` and `hashCode` defined, you can try using a `java.util.Set` instead of a List? – mabi Nov 29 '13 at 09:56
  • Are you using an EntityManager for persisting (saving)? – JamesB Nov 29 '13 at 09:57
  • set both source and destination as primary key (composite primary key).. and you dont need the auto-incremented id because based on your explaination, that id field is not your table id – David Nov 29 '13 at 09:57
  • 1
    Plus, can you post the code for the Route class? – JamesB Nov 29 '13 at 09:58
  • thanks mabi I was not using hashCode earlier but they can be useful here I will try that. – Amit Kumar Nov 29 '13 at 13:53

2 Answers2

2

This query counts how many ids have the same value:

SELECT COUNT(id), value
FROM table
GROUP BY value
T0to
  • 422
  • 2
  • 5
2

Searching for duplicate rows already persisted can lead to performance issues. For each new item you ill need to search a match in that table. To guarantee routes are unique you can create a unique index covering source and destination ids. Any attempt to duplicate data ill throw an exception. and this ill work fast.

But if all you want is to just find duplicate items in a list look at this post. How to find duplicate items in list

Community
  • 1
  • 1
jean
  • 4,159
  • 4
  • 31
  • 52
  • Your linked answer is using C# and Linq. Can you find something for Java? – mabi Nov 29 '13 at 11:02
  • HI thanks for your reply. I should make all other fields in composition as unique that will solve the problem as it will through unique constraint violation exception. Any better solution is welcome. – Amit Kumar Nov 29 '13 at 13:50