Search code examples
javahibernatemappingmany-to-many

put in hashmap using two lists and database


I have two classes, User and Customer, using hibernate, I have mapped these tables, now I want to retrieve the data from the database, where I can put the values in hashmap such that for each user, if a particular customer exists in the mapping table, then the key of map is set as the customer name, and value to true or false, depending upon the mapping table.

I have retrieved both the lists:

static List<User> listUsers = new ArrayList<User>();
static List<Customer> listCustomers = new ArrayList<Customer>();
List<UserTO> list = new ArrayList<UserTO>();

public static List<Customer> getListOfCustomers() {
    HibernateUtil.openSession();
    Session session = HibernateUtil.getSession();
    Transaction tx = null;
    try {
        tx = session.getTransaction();
        tx.begin();
        listCustomers = session.createQuery("from Customer").list();
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    } finally {
        session.close();
    }
    return listCustomers;
}
(similarly list of users)

in UserTO class, I have:

public class UserTO implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;

private String userId;
private Map<String, Boolean> map = new HashMap<String, Boolean>();
(getter and setter)

I tried doing this:

public static void execute() {
    getListOfUsers();
    getListOfCustomers();
    for (User user : listUsers) {
        UserTO u = new UserTO();
        Map<String, Boolean> map = new HashMap<>();
        for (Customer customer : listCustomers) {
            if (customer.getCompanyName() == user.getCustomers(customer)) {
                map.put(customer.getCompanyName(), true);
            } else {
                map.put(customer.getCompanyName(), false);
            }
        }
        user.getUserId();
        u.setUserId(user.getUserId());
        u.setMap(map);
        listUsers.add(user);
    }
}

which gives me Concurrent Modification Exception I don't know where I am doing wrong, and what should I do next.


Solution

  • you are adding user to listUsers when you are iterating over this listuser. This results in the given exception.

    Use list.add(u);