Java StringWriter

StringWriter is similar to StringBuffer, which can collect a host of string values and work with the data. We will explore writing a porting of a given string. Code sample: import;public class UsingStringWriter{ public static void main(String args[]) { UsingStringWriter usingStringWriter = new UsingStringWriter(); usingStringWriter.proceed(); } private void proceed()

Divide Two Positive Integers and Round Up

In Java, we can divide two positive integers and round up as follows: int result = (x + y – 1) / y Example: (4/3 = 1.33 and we want 2): long result = (4 + 3 – 1) / 3; // 2

Async Query Results

Repository queries can be executed asynchronously using @Async annotation. The result can be a Future, CompletableFuture and ListenableFuture. The method will return immediately upon invocation: @asyncFuture findByName(String name);@asyncCompletableFuture findByName(String name);@asyncListenableFuture findByName(String name);

Return a MappingJacksonValue from a REST Controller

A proof of concept can be seen below: @GetMapping(“…”)public MappingJacksonValue fooMethod(…) throws JsonProcessingException { List foos = …; MappingJacksonValue wrapper = new MappingJacksonValue(fooa); … return wrapper;}

Unwrapping a Session from EntityManager

When we need access to a Hibernate Session, we have to unwrap it from the current EntityManager via the unwrap() method as follows: // Spring and Java EE EntityManager em = …;Session session = em.unwrap(Session.class);

Selectively Expose CRUD Methods

When a repository interface should not be instantiated at runtime, it should be marked with @NoRepositoryBean annotation as follows: @NoRepositoryBeaninterface BaseRepository extends Repository { // CRUD methods that will not be exposed}

Avoid Jackson Lazy Init Exceptions

First, add the following dependency to your project (Maven): com.fasterxml.jackson.datatype jackson-datatype-hibernate5 ${jackson.version} Further, add the following bean: @Beanpublic Module datatypeHibernateModule() { return new Hibernate5Module();}

Finding the Mime Type of a File

Finding the MIME type of a file is useful when you want to perform certain actions. PS: I have placed a file named nature.jpg in the folder /home/sridhar before executing this class. Code sample: import java.nio.file.*;import*;public class FindMIMEType{ public static void main(String args[]) { FindMIMEType findMIMEType = new FindMIMEType();

How to Annotate Class with Lombok

The first approach consists of annotating the class as below: @[email protected]@[email protected]@RequiredArgsConstructorpublic class Foo { …} A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor is @Data as follows: @Datapublic class Foo { …}

No more posts to show