I believe that having the something.getDataList()
around is a clicking bomb if there are milions of Data
records related to Something
. Just as you said, calling something.getDataList().add(data)
would fetch the whole data set from DB in order to perform a single insert. Also, anyone could be tempted to use something.getDataList().size
to get the number of records, resulting in the same overhead.
My suggestion is that you use the DataDAO for such operations (i.e. adding or counting) like:
void addData(Something something, Data data){
//Something similar can be used for batch insert
data.setSomething(something);
em.persist(data);
}
List<Data> findData(Something something, MyFilter filter){
// use a NamedQuery with parameters populated by something and your filters
return em.getResultList();
}
Long countData(Something something){
// use a 'SELECT COUNT(*) FROM Data d WHERE d.something = :something' NamedQuery
return em.getSingleResult;
}