Map elements from "stream in stream" to Set - java

I'm new to Java streams.
I have an Array of n classes.
The classes have several fields with a particular annotation (SomeAnnotationClass.class)
I'm trying to get a Set of all the fields annotations values which are annotated with this particular annotation. If the field does not have the annotation I want the name of the field.
So i tried something like this:
Stream.of(clazzes).map( c ->
Stream.of((c.getDeclaredFields()))
.map(
field ->
Optional.ofNullable(
field.getDeclaredAnnotation(SomeAnnotationClass.class).value())
.orElse(field.getName())).collect(Collectors.toSet())).collect(Collectors.toSet());
2 issues with this:
I get a Set<Set> instead of Set due to collecting 2 times.
I get a Nullpointer if the annotation is not present but SomeAnnotationClass.class.value() is called
Can I achieve this elegantly with streams?

A set of sets should be flattened:
// in Main.java
public static Set<String> getValuesOrNames(Class ... clazzes) {
return Arrays.stream(clazzes) // convert array to Stream<Class>
.flatMap(c -> Arrays.stream(c.getDeclaredFields())) // convert array of fields Stream<Field>
.map(field -> Optional.ofNullable(field.getAnnotation(SomeAnnotationClass.class))
.map(SomeAnnotationClass::value) // assuming SomeAnnotationClass has value method
.orElse(field.getName())
)
.collect(Collectors.toSet());
}
Test
// annotation class
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
public #interface SomeAnnotationClass {
String value() default "";
}
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
public class Main {
public static void main(String[] args) {
System.out.println(getValuesOrNames(Something.class, Main.class));
}
#Data
public static class Something {
#SomeAnnotationClass(value = "String foo")
private String foo;
#SomeAnnotationClass
private String emptyFoo;
private String bar;
#SomeAnnotationClass(value = "int id")
private int id;
}
}
Output
[, String foo, bar, int id]

As mentioned by #Andy Turner, you can use to flatMap to map multiple streams into single stream and to avoid NPE check the annotation before accessing value()
Set<String> value = clazzes.stream().map(c -> Stream.of((c.getDeclaredFields()))
.map(field -> Optional.ofNullable(
field.getDeclaredAnnotation(SomeAnnotationClass.class)).map(SomeAnnotationClass::value).orElseGet(field::getName)).collect(Collectors.toSet()))
.flatMap(Collection::stream).collect(Collectors.toSet());

package io.falcon.instagram.indexer.util;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.Enumerated;
import javax.persistence.Id;
public class Example {
public static void main(String[] args) {
List<Class<?>> classes = List.of(Test.class);
Class<Enumerated> someAnnotationClass = Enumerated.class;
Set<String> fieldNames =
classes.stream()
.flatMap(c -> Arrays.stream(c.getDeclaredFields().clone())) // because getDeclaredFields returns array type
.map((Field field) -> Optional.ofNullable(field.getDeclaredAnnotation(someAnnotationClass)).map(a -> field.getName()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
System.out.println(fieldNames);
}
public static class Test {
#Id
private final String id;
#Id
#Enumerated
private final String field;
#Enumerated
private final String another;
#Enumerated
private final String theGame;
public Test(String id, String field, String another, String theGame) {
this.id = id;
this.field = field;
this.another = another;
this.theGame = theGame;
}
}
}

Related

json validator in Java - using javax.validation.constraints

I'm using javax.validation.constraints and have already checked the package usage but still can't find what I'd like to do.
https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/package-summary.html
Here are the two of the variables being sent from the request body
#NotNull
#PositiveOrZero
#Digits(integer = 9, fraction = 0)
private BigDecimal valueA;
#NotNull
#PositiveOrZero
#Digits(integer = 9, fraction = 0)
private BigDecimal valueB;
is it possible to restrict valueB to be not more than 50% of valueA by annotation only? (valueB <= valueA/2)
there are 2 approach to do that:
you can insert #AssertTrue method to validate it
#AssertTrue
public boolean isFiftyPercent(){
//your logic to compare value a and value b
}
or you can make your own annotation validation for global setting. see here: https://www.baeldung.com/spring-mvc-custom-validator
what you are looking for is using Cross-Parameter Constraints. some basic guide can be found here chapter 2.x
https://www.baeldung.com/javax-validation-method-constraints
You need to have a class level annotation for this. Field level annotations only access value of the fields.
Here is an example:
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
// Custom annotation
#Target({ TYPE })
#Retention(RUNTIME)
#Repeatable(NotGreaterThans.class)
#Documented
#Constraint(validatedBy = { NotGreaterThanValidator.class }) // Explicitly define validator
public #interface NotGreaterThan {
String source();
String target();
double percentage()
String message() default "Default message ..";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
#Target({ TYPE })
#Retention(RUNTIME)
#Documented
#interface NotGreaterThans {
NotGreaterThan[] value();
}
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
// Validator accesses both annotation and object value
public class NotGreaterThanValidator implements ConstraintValidator<NotGreaterThan, Object> {
private String source;
private String target;
private double percentage;
#Override
public void initialize(NotGreaterThan notGreaterThan) {
this.source = notGreaterThan.source();
this.target = notGreaterThan.target();
this.percentage = notGreaterThan.percentage();
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
BigDecimal sourceValue = customMethodToGetFieldValue(source, value);
BigDecimal targetValue = customMethodToGetFieldValue(target, value);
return source.compareTo(target.multiply(percentage)) <= 0;
}
private BigDecimal customMethodToGetFieldValue(String fieldName, Object object) {
return ....
}
}
// Define your annotation on type
#NotGreaterThan(source ="a", target="b", percentage =50.0)
public class MyCustomBodyClass {
private BigDecimal a;
private BigDecimal b;
}
I haven't tested this, but should give you a head start.

Jackson deserialize string to default enum [duplicate]

I am using REST web service/Apache Wink with Jackson 1.6.2. How do I annotate an enum field so that Jackson deserializes it?
Inner class
public enum BooleanField
{
BOOLEAN_TRUE { public String value() { return "1";} },
BOOLEAN_FALSE { public String value() { return "0";} },
Java Bean/Request object
BooleanField locked;
public BooleanField getLocked() {return locked;}
The Jackson docs state that it can do this via #JsonValue/#JsonCreator but provides no examples.
Anyone willing to spill the (java)beans, as it were?
If you are using Jackson 1.9, serialization would be done by:
public enum BooleanField {
BOOLEAN_TRUE("1")
;
// either add #JsonValue here (if you don't need getter)
private final String value;
private BooleanField(String value) { this.value = value; }
// or here
#JsonValue public String value() { return value; }
so change you need is to add method to Enum type itself, so all values have it. Not sure if it would work on subtype.
For #JsonCreator, having a static factory method would do it; so adding something like:
#JsonCreator
public static BooleanField forValue(String v) { ... }
Jackson 2.0 will actually support use of just #JsonValue for both, including deserialization.
With Jackson 2.6 or newer, the #JsonProperty annotation can be applied directly to the enum constant to change its serialization:
public enum BooleanField
{
#JsonProperty("1")
BOOLEAN_TRUE,
#JsonProperty("0")
BOOLEAN_FALSE
}
don't annotate them, just configure your ObjectMapper instance:
private ObjectMapper createObjectMapper() {
final ObjectMapper mapper = new ObjectMapper();
// enable toString method of enums to return the value to be mapped
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
return mapper;
}
and in your enum override the toString() method:
public enum SectionType {
START("start"),
MORE("more");
// the value which is used for matching
// the json node value with this enum
private final String value;
SectionType(final String type) {
value = type;
}
#Override
public String toString() {
return value;
}
}
You don't need any annotations or custom deserializers.
Actually, according to the docs for JsonValue (Jackson 2.3.3):
NOTE: when use for Java enums, one additional feature is
* that value returned by annotated method is also considered to be the
* value to deserialize from, not just JSON String to serialize as.
* This is possible since set of Enum values is constant and it is possible
* to define mapping, but can not be done in general for POJO types; as such,
* this is not used for POJO deserialization.
So for enums, your deserialization will not work using JsonCreator because JsonValue will be used for both serialization and deserialization.
One way to do this for enums is using JsonSetter and JsonGetter.
public enum BooleanField
{
BOOLEAN_TRUE("1"),
BOOLEAN_FALSE("0");
private final String value;
BooleanField( int value ) { this.value = value; }
}
Deserializer
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class BooleanFieldDeserializer extends Json Deserializer<BooleanField> {
public BooleanField deserialize( JsonParser p, DeserializationContext ctx )
throws IOException
{
// boilerplate code for every deserializer
ObjectCodec objectCodec = p.getCodec();
JsonNode node = objectCodec.readTree(p);
// customizable part for your impl
String booleanFieldString = node.asText();
return valueOf( booleanFieldString ); <- Enum-supplied method
}
Then, in your JavaBean...
#JsonDeserialize(using = BooleanFieldDeserializer.class)
BooleanField locked;
The following may work if the enumeration is an array or not. (Only for deserialization)
package com.stack.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.Data;
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonPropertyOrder({ "success", "my-enums" })
public class MyObjectJSON {
#JsonProperty("sucess")
private boolean success;
#JsonProperty("my-enums")
private MyEnum[] myEnums;
static enum MyEnum {
Enum1, Enum2, Enum3, Enum4, EnumN;
private static Map<String, MyEnum> myEnumsMap = new HashMap<String, MyEnum>(5);
static {
myEnumsMap.put("enum1-val", Enum1);
myEnumsMap.put("enum2-val", Enum2);
myEnumsMap.put("enum3-val", Enum3);
myEnumsMap.put("enum4-val", Enum4);
myEnumsMap.put("enumn-val", EnumN);
}
#JsonCreator
public static MyEnum forValue(String value) {
return myEnumsMap.get(value.toLowerCase());
}
}
}
To consider:
The #Data annotation generates setters, getters, toString, etc.
#JsonProperty("my-enums") private MyEnum[] myEnums, this is the way to annotate with jackson the field that is of type Enum (
It works if it is an array or not).
MyEnum is the enumeration of the values ​​to be mapped of the JSON object, suppose the following object:
{
"sucess": true,
"my-enums": ["enum1-val", "enum3-val"]
}
The forValue function allows mapping the string values ​​of the array to Enum, it is annotated with #JsonCreator to indicate a construction factory used in deserialization.

Jackson ObjectMapper setSerializationInclusion() not working

I'm just getting familiar with Jackson binding. However, when I'm testing setSerializationInclusion(JsonInclude.Include.NON_NULL), I found that it's not working sometimes.
Here is my code
package com.blithe.main;
import com.blithe.model.Student;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Jackson_2_NullValue {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Student s = new Student();
String stundetString = mapper.writeValueAsString(s);
System.out.println(stundetString);
// exclude null fields
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
s.setName("ss");
stundetString = mapper.writeValueAsString(s);
System.out.println(stundetString);
}
}
and the POJO
package com.blithe.model;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
// #JsonIgnoreProperties(ignoreUnknown = true)
// exclude null fields for the whole class
// #JsonInclude(Include.NON_NULL)
public class Student {
// exclude the field whe it's empty ("")
// #JsonInclude(value=Include.NON_EMPTY)
private String name;
private Integer age;
private Date birth;
// Jackson ignores it
#JsonIgnore
private String nickName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
the output is
{"name":null,"age":null,"birth":null}
{"name":"ss","age":null,"birth":null}
The later one should be null-value excluded, but it doesn't.
However, when I put my code this way.
package com.blithe.main;
import com.blithe.model.Student;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Jackson_2_NullValue {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Student s = new Student();
String stundetString = mapper.writeValueAsString(s);
System.out.println(stundetString);
// exclude null fields
// mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
s.setName("ss");
stundetString = mapper.writeValueAsString(s);
System.out.println(stundetString);
}
}
It works with the output below
{}
{"name":"ss"}
Is this normal or just some kind of bug? Do I miss anything? The only maven dependency is jackson-databind 2.7.4. Any discussion is welcomed. Thanks!
Do not change ObjectMappers settings while using it. Once mapper has been in use not all settings take effect, because of caching of serializers and deserializers.
Configure an instance once and do not change settings after first use. It is done this way for thread-safety and performance.
Update: Dead links replaced with archive.org ones
http://wiki.fasterxml.com/JacksonFAQThreadSafety
http://wiki.fasterxml.com/JacksonBestPracticesPerformance
So the point is if you are using ObjectMappers at multiple places, try not to create objects again and again. it takes the configs of first initialized.
if you keep changing on a global level it will not work.

How to annotate enum fields for deserialization using Jackson json

I am using REST web service/Apache Wink with Jackson 1.6.2. How do I annotate an enum field so that Jackson deserializes it?
Inner class
public enum BooleanField
{
BOOLEAN_TRUE { public String value() { return "1";} },
BOOLEAN_FALSE { public String value() { return "0";} },
Java Bean/Request object
BooleanField locked;
public BooleanField getLocked() {return locked;}
The Jackson docs state that it can do this via #JsonValue/#JsonCreator but provides no examples.
Anyone willing to spill the (java)beans, as it were?
If you are using Jackson 1.9, serialization would be done by:
public enum BooleanField {
BOOLEAN_TRUE("1")
;
// either add #JsonValue here (if you don't need getter)
private final String value;
private BooleanField(String value) { this.value = value; }
// or here
#JsonValue public String value() { return value; }
so change you need is to add method to Enum type itself, so all values have it. Not sure if it would work on subtype.
For #JsonCreator, having a static factory method would do it; so adding something like:
#JsonCreator
public static BooleanField forValue(String v) { ... }
Jackson 2.0 will actually support use of just #JsonValue for both, including deserialization.
With Jackson 2.6 or newer, the #JsonProperty annotation can be applied directly to the enum constant to change its serialization:
public enum BooleanField
{
#JsonProperty("1")
BOOLEAN_TRUE,
#JsonProperty("0")
BOOLEAN_FALSE
}
don't annotate them, just configure your ObjectMapper instance:
private ObjectMapper createObjectMapper() {
final ObjectMapper mapper = new ObjectMapper();
// enable toString method of enums to return the value to be mapped
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
return mapper;
}
and in your enum override the toString() method:
public enum SectionType {
START("start"),
MORE("more");
// the value which is used for matching
// the json node value with this enum
private final String value;
SectionType(final String type) {
value = type;
}
#Override
public String toString() {
return value;
}
}
You don't need any annotations or custom deserializers.
Actually, according to the docs for JsonValue (Jackson 2.3.3):
NOTE: when use for Java enums, one additional feature is
* that value returned by annotated method is also considered to be the
* value to deserialize from, not just JSON String to serialize as.
* This is possible since set of Enum values is constant and it is possible
* to define mapping, but can not be done in general for POJO types; as such,
* this is not used for POJO deserialization.
So for enums, your deserialization will not work using JsonCreator because JsonValue will be used for both serialization and deserialization.
One way to do this for enums is using JsonSetter and JsonGetter.
public enum BooleanField
{
BOOLEAN_TRUE("1"),
BOOLEAN_FALSE("0");
private final String value;
BooleanField( int value ) { this.value = value; }
}
Deserializer
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class BooleanFieldDeserializer extends Json Deserializer<BooleanField> {
public BooleanField deserialize( JsonParser p, DeserializationContext ctx )
throws IOException
{
// boilerplate code for every deserializer
ObjectCodec objectCodec = p.getCodec();
JsonNode node = objectCodec.readTree(p);
// customizable part for your impl
String booleanFieldString = node.asText();
return valueOf( booleanFieldString ); <- Enum-supplied method
}
Then, in your JavaBean...
#JsonDeserialize(using = BooleanFieldDeserializer.class)
BooleanField locked;
The following may work if the enumeration is an array or not. (Only for deserialization)
package com.stack.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.Data;
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonPropertyOrder({ "success", "my-enums" })
public class MyObjectJSON {
#JsonProperty("sucess")
private boolean success;
#JsonProperty("my-enums")
private MyEnum[] myEnums;
static enum MyEnum {
Enum1, Enum2, Enum3, Enum4, EnumN;
private static Map<String, MyEnum> myEnumsMap = new HashMap<String, MyEnum>(5);
static {
myEnumsMap.put("enum1-val", Enum1);
myEnumsMap.put("enum2-val", Enum2);
myEnumsMap.put("enum3-val", Enum3);
myEnumsMap.put("enum4-val", Enum4);
myEnumsMap.put("enumn-val", EnumN);
}
#JsonCreator
public static MyEnum forValue(String value) {
return myEnumsMap.get(value.toLowerCase());
}
}
}
To consider:
The #Data annotation generates setters, getters, toString, etc.
#JsonProperty("my-enums") private MyEnum[] myEnums, this is the way to annotate with jackson the field that is of type Enum (
It works if it is an array or not).
MyEnum is the enumeration of the values ​​to be mapped of the JSON object, suppose the following object:
{
"sucess": true,
"my-enums": ["enum1-val", "enum3-val"]
}
The forValue function allows mapping the string values ​​of the array to Enum, it is annotated with #JsonCreator to indicate a construction factory used in deserialization.

How can you use Builder Pattern for entities with JPA

I read that it's useful to use builder pattern when you have a class with a lot of parameters. I wonder how you can implement an entity using builder pattern. It would be great if you can provide sample code.
Of course it is possible, you just have to provide a (possibly nested) Builder for every Entity.
Here is a working example:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class FluentEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String someName;
private int someNumber;
private boolean someFlag;
protected FluentEntity(){}
private FluentEntity(String someName, int someNumber, boolean someFlag) {
this.someName = someName;
this.someNumber = someNumber;
this.someFlag = someFlag;
}
public long getId() {
return id;
}
public String getSomeName() {
return someName;
}
public int getSomeNumber() {
return someNumber;
}
public boolean isSomeFlag() {
return someFlag;
}
public static FluentEntityBuilder builder() {
return new FluentEntityBuilder();
}
public static class FluentEntityBuilder {
private String someName;
private int someNumber;
private boolean someFlag;
public FluentEntityBuilder setSomeName(final String someName) {
this.someName = someName;
return this;
}
public FluentEntityBuilder setSomeNumber(final int someNumber) {
this.someNumber = someNumber;
return this;
}
public FluentEntityBuilder setSomeFlag(final boolean someFlag) {
this.someFlag = someFlag;
return this;
}
public FluentEntity build() {
return new FluentEntity(someName, someNumber, someFlag);
}
}
}
The code to use it would be this:
FluentEntity entity = FluentEntity.builder().setSomeName(someName).setSomeNumber(someNumber)
.setSomeFlag(someFlag).build();
Just keep in mind that you have to exclude auto-generated fields like the primary key (in this example id) if you have some.
If you want to get rid of the "boilerplate" code for creating Builder classes for every Entity I would recommend a convenience library, something like Lombok. Then you will get your Builders (and even more) by just annotating your Entites, maybe it costs a little extra work to exclude the id fields.
You should take a look at Project Lombok
Nevertheless, here is some code to test this Builder (implemented with Spring Boot and Hibernate).
The repository:
import org.springframework.data.repository.CrudRepository;
import com.example.model.FluentEntity;
public interface FluentEntityRepository extends CrudRepository<FluentEntity, Long> {
}
And here are some tests:
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import java.util.stream.StreamSupport;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.example.model.FluentEntity;
#RunWith(SpringRunner.class)
#Transactional
#SpringBootTest
public class FluentEntityRepositoryTests {
#Autowired
private FluentEntityRepository fluentEntityRepository;
#Test
public void insertAndReceiveFluentEntityCreatedWithBuilder() {
final String someName = "name";
final int someNumber = 1;
final boolean someFlag = true;
FluentEntity entity = FluentEntity.builder().setSomeName(someName).setSomeNumber(someNumber)
.setSomeFlag(someFlag).build();
entity = fluentEntityRepository.save(entity);
assertThat("Entity did not get a generated Id!", entity.getId(), greaterThan(-1L));
assertThat("Entity name did not match!", entity.getSomeName(), is(someName));
assertThat("Entity number did not match!", entity.getSomeNumber(), is(someNumber));
assertThat("Entity flag did not match!", entity.isSomeFlag(), is(someFlag));
}
#Test
public void insertSomeAndReceiveFirst() {
fluentEntityRepository.save(FluentEntity.builder().setSomeName("A").setSomeNumber(1).setSomeFlag(true).build());
fluentEntityRepository
.save(FluentEntity.builder().setSomeName("B").setSomeNumber(2).setSomeFlag(false).build());
fluentEntityRepository.save(FluentEntity.builder().setSomeName("C").setSomeNumber(3).setSomeFlag(true).build());
final Iterable<FluentEntity> findAll = fluentEntityRepository.findAll();
assertThat("Should get some iterable!", findAll, notNullValue());
final FluentEntity fluentEntity = StreamSupport.stream(findAll.spliterator(), false).findFirst().get();
assertThat("Should get some entity!", fluentEntity, notNullValue());
}
}

Categories