Search code examples
javajpajpql

How to instantiate a object with a constructor that takes long if table only contains null?


im trying to do this query, but get IllegalArgumentException when trying to instantiate my PassageStatistics object that takes long parameters in its constructor, when the table is empty (only contains null values), here's the quering method in repository class:

@SuppressWarnings("unchecked")
@Override
public PassageStatistics getPassageStatisticsForAllStations() {
    Query query = 
            em.createQuery("SELECT NEW com.henrikpetersson.cartoll.tolldomain.domain.PassageStatistics(count(p), sum(price)) from Passage p");

    return (PassageStatistics) query.getSingleResult();
}

Here's the PassageStatistics object:

public class PassageStatistics {

    private long passageCount;
    private long revenue;

    public PassageStatistics(long passageCount, long revenue) {
        this.passageCount = passageCount;
        this.revenue = revenue;
    }

      public PassageStatistics() {}

}

What is best practise ? Should i use the wrapper Long, invoke getPassageStatisticsForAllStations in a try and catch in my service class and handle the exception there or make 2 queries ?

Thanks on forehand!


Solution

  • If you are required to accept null as a valid value in the constructor then the types of your parameters must be objects, which means the answer to your question is yes, you should use (Long, Long).

    As pointed out in the comments, it would be reasonable to have a default value specified in your bean that you would use if the value passed in the constructor is null. Something like this would work:

    public class PassageStatistics {
    
        private static final Long DEFAULT_PASSAGE_COUNT = 0;
        private static final Long DEFAULT_REVENUE = 0;
        private long passageCount;
        private long revenue;
    
        public PassageStatistics(Long passageCount, Long revenue) {
            this.passageCount = passageCount == null ? DEFAULT_PASSAGE_COUNT : passageCount;
            this.revenue = revenue == null ? DEFAULT_REVENUE : revenue;
        }
    }