You can either add an @AllArgsConstructor annotation, because
@Buildergenerates an all-args constructor if there are no other constructors defined.
(Quoting @Andrew Tobilko)
Or set an attribute to @Builder : @Builder(toBuilder = true) This give you the functionality of a copy constructor.
@Builder(toBuilder = true)
class Foo {
// fields, etc
}
Foo foo = getReferenceToFooInstance();
Foo copy = foo.toBuilder().build();
Answer from Gavrilo Adamovic on Stack Overflowjava - Why is Lombok @Builder not compatible with this constructor? - Stack Overflow
Spring boot Lombok and Builder, please help a junior
java - lombok @Builder vs constructor - Stack Overflow
java - Lombok @Builder and JPA Default constructor - Stack Overflow
Videos
You can either add an @AllArgsConstructor annotation, because
@Buildergenerates an all-args constructor if there are no other constructors defined.
(Quoting @Andrew Tobilko)
Or set an attribute to @Builder : @Builder(toBuilder = true) This give you the functionality of a copy constructor.
@Builder(toBuilder = true)
class Foo {
// fields, etc
}
Foo foo = getReferenceToFooInstance();
Foo copy = foo.toBuilder().build();
When you provide your own constructor then Lombok doesn't create a constructor with all args that @Builder is using. So you should just add annotation @AllArgsConstructor to your class:
@Data //try to avoid as it's an anti-pattern
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RegistrationInfo {
//...
}
What exactly does @ Builder annotation do? I need to deliver JUnit tests (it's my first contact with tests) of a really small challenge project, but without using Lombok and I'm not finding tutorials that don't use @ Builder to do them. Thanks in advance.
ps: english it's not my first language, sorry
edit: thank you all very much for the help, I managed to solve the problem through the documentation and some videos
Consider:
Order order = new Order("Alan", "Smith", 2, 6, "Susan", "Smith");
What do the parameters mean? We have to look at the constructor spec to find out.
Now with a builder:
Order order = Order.builder()
.originatorFirstName("Alan")
.originatorLastName("Smith")
.lineItemNumber(2)
.quantity(6)
.recipientFirstName("Susan")
.recipientLastName("Smith")
.build();
It's more wordy, but it's very clear to read, and with IDE assistance it's easy to write too. The builders themselves are a bit of a chore to write, but code-generation tools like Lombok help with that.
Some people argue that if your code needs builders to be readable, that's exposing other smells. You're using too many basic types; you're putting too many fields in one class. For example, consider:
Order order = new Order(
new Originator("Alan", "Smith"),
new ItemSet(new Item(2), 6),
new Recipient("Susan", "Smith"));
... which is self-explanatory without using a builder, because we are using more classes with single-responsibilities and fewer fields.
This is not a lombok specific feature, this is called a builder pattern.
Imagine you have a class with 20 parameters, and 10 of them are optional. You could somehow make tons of constructors taking care of this logic, or make a constructor with all those arguments and pass nulls in some places. Isn't builder pattern simply easier?
Updated
Based on the feedback and John's answer I have updated the answer to no longer use @Tolerate or @Data and instead we create accessors and mutators via @Getter and @Setter, create the default constructor via @NoArgsConstructor, and finally we create the all args constructor that the builder requires via @AllArgsConstructor.
Since you want to use the builder pattern I imagine you want to restrict visibility of the constructor and mutators methods.
To achieve this we set the visibility to package private via the access attribute on the @NoArgsConstructor and @AllArgsConstructor annotations and the value attribute on the @Setterannotation.
Important
Remember to properly override toString, equals, and hashCode.
See the following posts by Vlad Mihalcea for details:
- the-best-way-to-implement-equals-hashcode-and-tostring-with-jpa-and-hibernate
- how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier
- hibernate-facts-equals-and-hashcode
package com.stackoverflow.SO34299054;
import static org.junit.Assert.*;
import java.util.Random;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.junit.Test;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@SuppressWarnings("javadoc")
public class Answer {
@Entity
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PACKAGE)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@Setter(value = AccessLevel.PACKAGE)
@Getter
public static class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/*
* IMPORTANT:
* Set toString, equals, and hashCode as described in these
* documents:
* - https://vladmihalcea.com/the-best-way-to-implement-equals-hashcode-and-tostring-with-jpa-and-hibernate/
* - https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
* - https://vladmihalcea.com/hibernate-facts-equals-and-hashcode/
*/
}
/**
* Test person builder.
*/
@Test
public void testPersonBuilder() {
final Long expectedId = new Random().nextLong();
final Person fromBuilder = Person.builder()
.id(expectedId)
.build();
assertEquals(expectedId, fromBuilder.getId());
}
/**
* Test person constructor.
*/
@Test
public void testPersonConstructor() {
final Long expectedId = new Random().nextLong();
final Person fromNoArgConstructor = new Person();
fromNoArgConstructor.setId(expectedId);
assertEquals(expectedId, fromNoArgConstructor.getId());
}
}
Old Version using @Tolerate and @Data:
Using @Tolerate worked to allow adding a noarg constructor.
Since you want to use the builder pattern I imagine you want to control visibility of the setter methods.
The @Data annotation makes the generated setters public, applying @Setter(value = AccessLevel.PROTECTED) to the fields makes them protected.
Remember to properly override toString, equals, and hashCode.
See the following posts by Vlad Mihalcea for details:
- the-best-way-to-implement-equals-hashcode-and-tostring-with-jpa-and-hibernate
- how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier
- hibernate-facts-equals-and-hashcode
package lombok.javac.handlers.stackoverflow;
import static org.junit.Assert.*;
import java.util.Random;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Tolerate;
import org.junit.Test;
public class So34241718 {
@Builder
@Data
public static class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Setter(value = AccessLevel.PROTECTED)
Long id;
@Tolerate
Person() {}
/* IMPORTANT:
Override toString, equals, and hashCode as described in these
documents:
- https://vladmihalcea.com/the-best-way-to-implement-equals-hashcode-and-tostring-with-jpa-and-hibernate/
- https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
- https://vladmihalcea.com/hibernate-facts-equals-and-hashcode/
*/
}
@Test
public void testPersonBuilder() {
Long expectedId = new Random().nextLong();
final Person fromBuilder = Person.builder()
.id(expectedId)
.build();
assertEquals(expectedId, fromBuilder.getId());
}
@Test
public void testPersonConstructor() {
Long expectedId = new Random().nextLong();
final Person fromNoArgConstructor = new Person();
fromNoArgConstructor .setId(expectedId);
assertEquals(expectedId, fromNoArgConstructor.getId());
}
}
You can also solve it explicitly with @Data @Builder @NoArgsConstructor @AllArgsConstructor combined on the class definition.