开发者

How to use the distinct on databases DB4O in Java?

Who ca开发者_开发百科n tell me how to use Distinct operation on db4o in Java code. I couldn't find any example in Java.

Thanks!


Afaik, there's no build in distinct-operator. You need to use a work-around. For example you can use a Set for the distinct-operation:

Distinct by the equality of the objects. When your class has a proper equals()- and hashCode()-Implementation, this works wonderful:

ObjectSet<TestClass> result = container.query(TestClass.class);
// will use the equals-method of TestClass.
Set<TestClass> distinctResult = new HashSet<TestClass>(result);

Distinct by a certain field. Useful when your want to make it distinct by a certain field.

ObjectSet<TestClass> result = container.query(TestClass.class);
Set<TestClass> distinctResultByField = new TreeSet<TestClass>(new Comparator<TestClass>() {
    public int compare(TestClass o1, TestClass o2) {
       return o1.getTestField().compareTo(o2.getTestField());
    }
});
distinctResultByField.addAll(result);


I wanted a select from ... order by... distinct query. Here is how I did it:

public static List<Country> getAllCountries(final CountryOrder order)
{
   ObjectContainer oc = DbHelper.getInstance().getContainer();
   ObjectSet<Country> countries = oc.query(new Predicate<Country>()
   {
      HashSet<Country> distinctCountries = new HashSet<Country>();

      @Override
      public boolean match(Country et)
      { // Need this to make a distict query... sad
         if (distinctCountries.contains(et))
         {
            return false;
         }

         distinctCountries.add(et);
         return true;
      }
   }, new Comparator<Country>()
   {
      @Override
      public int compare(Country o1, Country o2)
      {
         switch (order)
         {
            case COUNTRY_CODE:
               return o1.getCountryCode().compareTo(o2.getCountryCode());
            case COUNTRY_NAME:
               return o1.getCountryName().compareTo(o2.getCountryName());
            default:
               return o1.compareTo(o2);
         }
      }
   });

   return countries;
}

In retrospect, you could use any container instead of the HashSet for distinctCountries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜