Save to a LinkedHashSet <String> - BEGINNER
@Override
public LinkedHashSet <String> listHotels() {
Query query = em.createNativeQuery("select * from Hotel");
LinkedHashSet <String> hotel= query.getResultList();
return hotel;
}
I am getting a Warning saying incompatible types. query.getResultList(); returns a List
, 开发者_如何转开发but what I want the method to return is a LinkedHashSet
.
The reason why I'm using a LinkedHashSet
here, is to avoid duplicate values being entered to the DB. I will call the method listHotels()
first, and check if it has already contains the value and if doesn't I'll save the values to the DB
EDIT
public void saveHotel(Hotel hotel) {
if (hotel.getId() ==null){
em.persist(hotel);
} else {
em.merge(hotel);
}
}
THis is how i save records to my DB
You cannot change the result type of query.getResultList(), but you can convert the List to a LinkedHashSet
:
LinkedHashSet<String> hotel= new LinkedHashSet(query.getResultList());
(The LinkedHashSet created will have the unique elements from the list. But the example you have shown is a SELECT sql, rather than an INSERT/UPDATE. To guarantee unique records on the database, you have to make such an arrangement - using a LinkedHashSet or so - in the INSERT/UPDATE part. If you are already using a LinkedHashSet
to add to the database, the database won't have duplicate records anyway. BTW, you have the necessary unique constraints on the database right?)
You can not map a List to a Set. If you just want to eliminate duplicate then you can do so using your DB query
精彩评论