valchkou / cassandra-driver-mapping

JPA addon for DataStax Java Driver for Cassandra
58 stars 24 forks source link

Default constructor necessary #56

Open czellweg opened 9 years ago

czellweg commented 9 years ago

Hey mate

Great library, we have just started using it and it works like a charm so far! Thank you for your continued effort.

I've just spend a while figuring out why I wasn't able to read data from the database as there was no exception and everything seemed to have worked. The issue turned out to be that there needs to be a default constructor for the mapping class, i.e. the class we wish to populate the values from the database with.

Long story short: in com.datastax.driver.mapping.builder.MappingBuilder.getFromRow(Class<T>, Row):533 where you create a new instance based on the class object of the entity one wishes to map values to

...
// create PK
try {
      entity = clazz.newInstance();
      PrimaryKeyMetadata pkmeta = entityMetadata.getPrimaryKeyMetadata();
...

if there is no default constructor of the entity, the entity reference will remain null. The javadoc also mentions this: Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. Hence, this does not lead to an exception when we set the database values in the following for-loop

...
if (field.isPartition()) {
       field.setValue(partitionKey, value);
} else if (field.isPrimary()) {
       field.setValue(primaryKey, value);
} else {
       field.setValue(entity, value);
}
...

Suggestion: In case a default constructor is absent, maybe throw an exception or log a statement so the user has a better idea what is going on?

valchkou commented 9 years ago

Thanks for comments, this is a valid concern. I initially started project with the minimum or no custom logging and error handling. But as more and more people use it I should consider adding meaningful messages to it.

Thanks for the story, I am sorry I have to figure it hard way

wilsondy commented 9 years ago

Also, for those who might follow, if you don't have any constructor defined, Java adds the default constructor, which means this package will work (similar to all the test cases). Once you add your own, the default one is removed and this issue will occur.