JavaRush /Java Blog /Random EN /Spring is not scary, in short: Lombok
Павел
Level 11

Spring is not scary, in short: Lombok

Published in the Random EN group
CONTENTS OF THE CYCLE OF ARTICLES A little bit of Wikipedia: Lombok (Lombok from Indonian - “chili pepper”) is an island in the Malay Archipelago, in the group of the Lesser Sunda Islands, part of Indonesia. Lombok is the name given to a popular library for the Java programming language. The choice of name is due to the fact that the island of Lombok is not so far from the island of Java, and also, apparently, with the meaning of its name "chili pepper", since the library provides useful "seasoning" for the language. You can’t say it better, and what’s the use of words, let’s see it in action: Install the plugin. Add a dependency to the <dependencies> block of the pom file:
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
Here we go: Open the project from the previous article , open the class FruitEntity .
package ru.java.rush.entities;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

@Entity
@Table(name = "fruit_table")
public class FruitEntity {

    @Id
    @Column(name = "id_fruit")
    @GenericGenerator(name = "generator", strategy = "increment")
    @GeneratedValue(generator = "generator")
    private Integer id;

    @Column(name = "fruit_name")
    private String fruitName;

    @Column(name = "provider_code")
    private Integer providerCode;

//чтобы с классом можно было совершать манипуляции создается
//пустой конструктор, геттеры, сеттеры, конструктор и переопределяется метод toString()

public FruitEntity(){

}


public Integer getId() {
    return id;
}

public FruitEntity setId(Integer id) {
    this.id = id;
    return this;
}

public String getFruitName() {
    return fruitName;
}

public FruitEntity setFruitName(String fruitName) {
    this.fruitName = fruitName;
    return this;
}

public Integer getProviderCode() {
    return providerCode;
}

public FruitEntity setProviderCode(Integer providerCode) {
    this.providerCode = providerCode;
    return this;
}

@Override
public String toString() {
    return "FruitEntity{" +
            "id=" + id +
            ", fruitName='" + fruitName + '\'' +
            ", providerCode=" + providerCode +
            '}';
}
A little long, isn't it? Let's add the @Data annotation from Lombok to the class and see how it shortens the code.
package ru.java.rush.entities;

import lombok.Data;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

@Data//annotation сгенирует при компиляции необходимый code
@Entity
@Table(name = "fruit_table")
public class FruitEntity {

    @Id
    @Column(name = "id_fruit")
    @GenericGenerator(name = "generator", strategy = "increment")
    @GeneratedValue(generator = "generator")
    private Integer id;

    @Column(name = "fruit_name")
    private String fruitName;

    @Column(name = "provider_code")
    private Integer providerCode;

//и все! Весь остальной code будет сгенирован Ломбоком
Run the project, check that everything works. Now let's see how you can inject a dependency using Lombok. Let's open class FruitService as an example , attach @RequiredArgsConstructor to the class and remove the constructor from the class; we no longer need it.
package ru.java.rush.services;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ru.java.rush.entities.FruitEntity;
import ru.java.rush.repositories.FruitRepository;

import java.util.List;


@Service
@RequiredArgsConstructor//annotation от Ломбок
public class FruitService {

    private final FruitRepository fruitRepository;

//здесь когда то был конструктор

    public Optional<FruitEntity> getById(Integer id) {
        return fruitRepository.findById(id);
    }

    public void delById(Integer id) {
        fruitRepository.deleteById(id);
    }

    public Boolean exist(Example<? extends FruitEntity> example) {
        return fruitRepository.exists(example);
    }

    public void save(FruitEntity fruitEntity) {
        fruitRepository.save(fruitEntity);
    }

    public List<FruitEntity> getAll() {
        return fruitRepository.findAll();
    }

    public void saveAll(List<FruitEntity> fruits) {
        fruitRepository.saveAll(fruits);
    }
Now use the same method to get rid of unnecessary code in the InitiateUtils class. Check that everything is working. As this project progresses, we are using several more new Lombok annotations. UPD: Good comment from Denis Ryabchikov "For an entity, it is better not to use @Data, but replace it with @Setter and @Getter, because @Data also overrides toString() and hashCode(), and problems may arise with the hash code if the entity will have collections and relationships with other entities." In principle, that’s all, here’s an article on Lombok , look at the description of the annotations: @Data, @Value, @RequiredArgsConstructor and @Builder. In this article, read about @ Accessors , the article is in English, but the page translator can handle it well, you can understand the meaning. In the next article we will continue to fill the database.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION