Skip to content

Instantly share code, notes, and snippets.

@mainul35
Created February 27, 2024 08:55
Show Gist options
  • Save mainul35/a03ab50eabfdc46fd8d1419f317bfc0f to your computer and use it in GitHub Desktop.
Save mainul35/a03ab50eabfdc46fd8d1419f317bfc0f to your computer and use it in GitHub Desktop.
Initialize an instance of a record without initializing all the properties - by using builder class
package com.mainul35.entity.order;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.math.BigDecimal;
/**
* Represents an item in the order.
*/
@Document(collection = "items")
public record Item(
@Id
/**
* The unique identifier for the item.
*/
@Field("_id")
String itemId,
/**
* The name of the item.
*/
@Field("item_name")
@JsonProperty("item_name")
String itemName,
/**
* The code of the item.
*/
@Field("item_code")
@JsonProperty("item_code")
String itemCode,
/**
* The price of the item.
*/
@Field("item_price")
@JsonProperty("item_price")
BigDecimal price,
/**
* The image of the item.
*/
@Field("item_image")
@JsonProperty("item_image")
String itemImage
) {
public static ItemBuilder builder () {
return new ItemBuilder();
}
/**
* Builder class for creating instances of {@link Item}.
*/
public static class ItemBuilder {
private String itemId;
private String itemName;
private String itemCode;
private BigDecimal price;
private String itemImage;
/**
* Sets the name of the item.
*
* @param itemId The name of the item.
* @return The {@link ItemBuilder} instance.
*/
public ItemBuilder itemId(String itemId) {
this.itemId = itemId;
return this;
}
/**
* Sets the name of the item.
*
* @param itemName The name of the item.
* @return The {@link ItemBuilder} instance.
*/
public ItemBuilder itemName(String itemName) {
this.itemName = itemName;
return this;
}
/**
* Sets the name of the item.
*
* @param itemCode The name of the item.
* @return The {@link ItemBuilder} instance.
*/
public ItemBuilder itemCode(String itemCode) {
this.itemCode = itemCode;
return this;
}
/**
* Sets the name of the item.
*
* @param itemImage The name of the item.
* @return The {@link ItemBuilder} instance.
*/
public ItemBuilder itemImage(String itemImage) {
this.itemImage = itemImage;
return this;
}
/**
* Sets the price of the item.
*
* @param price The price of the item.
* @return The {@link ItemBuilder} instance.
*/
public ItemBuilder price(BigDecimal price) {
this.price = price;
return this;
}
/**
* Constructs an {@link Item} object with the set properties.
*
* @return The created {@link Item} object.
*/
public Item build() {
return new Item(itemId, itemName, itemCode, price, itemImage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment