I am new to spring-boot. I have a spring boot app and frontend in Angular 8 and postgres DB. I am using MapStruct
for mapping between entity and DTO. I have a Product
entity and creating new record and updating works fine. Now I want to include image in the entity also to be saved in DB. I have searched and found everybody is saying to use MultipartFile
method but every solution contains only saving of image and not the entity data. Is there a way to save image along with entity properties? How does MapStruct behaves along with image as the image needs to be included in DTO? Any solutions?
Product
@Entity
@Table(name = "products", indexes = {@Index(name= "part_number_index", columnList = "part_number", unique = true)})
public class Product extends UserDateAudit
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(name = "part_number", nullable = false)
@Size(max = 20)
private String partNumber;
@NotBlank
@Size(max = 255)
private String description;
@OneToMany(
mappedBy = "product",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
orphanRemoval = true
)
@Fetch(FetchMode.SELECT)
private List<ReplaceNumber> replaceNumbers = new ArrayList<>();
@ManyToOne
@JoinColumn(name = "product_manufacturer_id", referencedColumnName = "id")
private ProductManufacturer manufacturer;
@ManyToOne
@JoinColumn(name = "product_model_id", referencedColumnName = "id")
private ProductModel model;
@ManyToOne
@JoinColumn(name = "product_category_id", referencedColumnName = "id")
private ProductCategory category;
@Column(name = "cost", nullable = false)
@DecimalMin(message = "Cost should be greater than 1", value = "1")
private float cost;
@Column(name = "price", nullable = false)
@DecimalMin(message = "Price should be greater than 0", value = "0")
private float price;
@Lob
private byte[] image;
}
Mapstruct knows the concept of update mappings. Checkout the MapStruct Documentation. You can reuse the current mappings my means of @InheritConfiguration
.
So
@Mapper
public interface MyMapper {
// create method
@Mapping( target = "field1", source ="fieldA" )
@Mapping( target = "field2", source ="fieldB" )
Entity map( Dto in );
// update method
@InheritConfiguraton
void map( Dto in, @MappingTarget Entity out );
}