Monday, 14 August 2017

How to retain/get only the duplicate elements in a list ~ foundjava

Let’s say you have a list of duplicate (and non-duplicate) items, and you want a new collection with only the duplicate items in there. The easiest way is to extend the HashSet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class DuplicatesOnlySet<E> extends HashSet<E>
{
    private final Set<E> uniques = new HashSet<E>();
 
    public  DuplicatesOnlySet(Collection<? extends E> c)
    {
        super.addAll(c);
    }
 
    @Override
    public boolean add(E e)
    {               
        if(!this.uniques.add(e))
             return super.add(e);
 
    return false;
    }
}
Call it like
1
List<String> duplicates = new ArrayList<String>(new DuplicatesOnlySet<String>(original)) ;
where original is the Collection with the duplicate items.
Read More »

org.hibernate.MappingException: broken column mapping for ~ foundjava

I got this error when I tried to map a child element by using its parent’s foreign key. I had a parent element with a region id (as foreign key) and I needed to get the child element whose primary key was this region id (and a language id). My child element (Region.hbm.xml) had a composite primary key
1
2
3
4
<composite-id>
            <key-property name="regionCode" type="integer" column="RGNCDE"/>
            <key-property name="languageCode" type="integer" column="LNGCDE"/>
        </composite-id>
and in my parent I did
1
2
3
<property name="regionCode" column="REGCDE" type="integer"/>
 
<many-to-one name="region" class="my.package.hbm.Region">
but this resulted in “org.hibernate.MappingException: broken column mapping for” error.
I had to split the child’s composite key
1
2
3
4
5
<id name="regionCode" type="integer" column="RGNCDE">
            <generator class="assigned"/>
        </id>
 
        <property name="languageCode" column="LNGCDE" type="integer"/>
and add a formula property in my parent’s class mapping
1
2
3
<property name="regionCode" column="REGCDE" type="integer"/>
 
<many-to-one name="region" class="my.package.hbm.Region" formula="REGCDE"/>
so that hibernate could link the region id of the parent to the region id of the child. And since I needed a record based also on the language code (but my parent didn’t have any language code column) I had to manually add search criteria
1
crit.createCriteria("region").add(Restrictions.eq("languageCode", 1));
Read More »