How to create a list of objects using a range of numbers in Java 8

The Java 8 Stream API could come in handy when you would like to generate a series of objects for example for using them in a unit test.

The following snippet generates a list of 5 User objects with the id and name populated:

List<User> users = IntStream.range(0, 5).mapToObj(i -> {

    User user = new User();
    user.setId(i);
    user.setName(USER_NAME_PREFIX + String.valueOf(i));

    return user;

}).collect(Collectors.toList());

If you have a suitable constructor, you can even make it a lot shorter:

List<User> users = IntStream.range(0, 5)
    .mapToObj(i -> new User(i, USER_NAME_PREFIX + String.valueOf(i)))
    .collect(Collectors.toList());

 

How to query count from a cassandra table using the DataStax Java Driver

Querying the count of rows from a Cassandra table in a Java application could be a bit tricky, because you can’t use the com.datastax.driver.mapping.Result<T> return type with the returned Long value returned by the count.

If you are trying to do that you could get an exception containing something like this:

@Table annotation was not found on class java.lang.Long

Yes the Result<T> type can only be used if you have a @Table annotated class. But this solution is not for returning counts.

To return the count, you have to use com.datastax.driver.core.ResultSet as your return type. You could have a query like this in your @Accessor interface.

@Accessor
public interface MyAccessor {

    @Query("SELECT COUNT(*) FROM tableName")
    ResultSet countAll();

}

Then, in your DAO, where you use this accessor, you can do the following to get the long value:

long count = this.myAccessor.countAll().one().getLong(0);

 

How to remove unnecessary trailing zeros from the string representation of a number

Recently I have had an issue where I needed to display some numbers that was sent to an application as strings. A lot of these numbers had some unnecessary trailing zeros at the end. I needed to remove these zeros, but keep the precision of the numbers.

The BigDecimal class came to my help. I converted my strings to BigDecimal instances and I was able to remove the unnecessary zeros and get back a string again the following way:

new BigDecimal("123.45600").stripTrailingZeros().toPlainString()

The result of this is another string, but without the trailing zeros.

"123.456"

This works with any other number, it won’t loose precision, just removes unnecessary zeros.

Codec not found for requested operation: [date <-> java.util.Date] exception in Cassandra

I was trying to create an Accessor interface in a Java application communicating with cassandra. The interface looked something like this:

import java.util.Date;

import com.datastax.driver.mapping.Result;
import com.datastax.driver.mapping.annotations.Accessor;
import com.datastax.driver.mapping.annotations.Query;
import com.custom.package.Order;

@Accessor
public interface OrderAccessor {

    @Query("SELECT * FROM orders WHERE checkout_date = ?")
    Result<Order> findAllOrdersByCheckoutDate(Date checkoutDate);

}

When I was trying to run the query, I got the following exception:

Codec not found for requested operation: [date <-> java.util.Date]

It turned out that for the Cassandra date type, the correct Java type to use is com.datastax.driver.core.LocalDate

Changing my java.util.Date to this resolved the issue.

IntelliJ reports that there is more than one bean of a repository, although app starts up fine

I’ve come across an issue recently in a project where I was using Spring Data JPA. I had a repository defined like this:

@Repository
public interface QuestionCategoryRepository extends JpaRepository<QuestionCategory, Long> {

}

I also had a service class where I injected this repository:

@Inject
private QuestionCategoryRepository questionCategoryRepository;

I noticed, that IntelliJ reported the following error: “There is more than one bean of QuestionCategoryRepository type”. It seemed wierd to me, so I went ahead and started my application. The context was built successfully and there were no problems with the startup at all.

It turned out that IntelliJ really had provided me a useful hint, because I noticed that I have an

@ComponentScan(basePackages = "...")

annotation on my class that is used for persistence related configuration. The scope of this annotation was involving the package where I had my repositories defined.

This is why IntelliJ believed, that there are two definitions.

Actually, there were three.

I also noticed that I have

@EnableJpaRepositories(basePackages = "...")

on my configuration class, pointing to the packes where my repositories reside.

It turned out that I can remove both the @Repository annotation and the @ComponentScan as well, becauses the @EnableJpaRepositories was enough to detect my repositories. Of course, @ComponentScan might need to be kept if it is for scanning some other classes.