Data On Init With Spring Command Line Runner

Viewed 320

Here , I want to hardcode some things into db at the action of server starts with Spring commandline runner

Problem :- In this I have checked that if 1L isn't present then do entry for that with Id 1L but still it stores to incremental Id when 1L or 2L or 3L is not present there.

My Entity In which I'm doing entry :-

Product Type

@Data
@Entity
@Table(name = "tbl_product_type_chemical")
public class ProductType implements IBaseData<Long> {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Long id;
    private String name;
    @Column(columnDefinition = "text")
    private String description;
    }

This is method of Runner :-

private void loadProductTypeNew() throws Exception {
    String SUBMODULE = " [Init Data] " + " [loadProductTypeNew()] ";
    try {
        ProductType fp = productTypeRepository.getOne(1L);
        if (null == fp) {
            fp = new ProductType();
            fp.setId(1L);
            fp.setName("FINISH PRODUCT");
            productTypeRepository.save(fp);
        }
        ProductType rm = productTypeRepository.getOne(2L);
        if (null != rm) {
            rm = new ProductType();
            rm.setId(2L);
            rm.setName("RAW MATERIAL");
            productTypeRepository.save(rm);
        }
        ProductType sm = productTypeRepository.getOne(3L);
        if (null != sm) {
            sm = new ProductType();
            sm.setId(3L);
            sm.setName("SUPPORTING MATERIAL");
            productTypeRepository.save(sm);
        }
    } catch (Exception ex) {
        ApplicationLogger.logger.error(SUBMODULE + ex.getMessage(), ex);
        throw ex;
    }
}


@Override
public void run(String... args) throws Exception {
    loadProductTypeNew();`
}

Output :-

9           SUPPORTING MATERIAL
8           RAW MATERIAL
7           FINISH PRODUCT
10          FINISH PRODUCT
11          RAW MATERIAL
12          SUPPORTING MATERIAL
13          RAW MATERIAL
14          SUPPORTING MATERIAL

And I am calling it in run method.If anyone can solve thanks in advance

1 Answers

Nothing in your application should depend on specific values of the id field since it is generated by the database.

I suggest therefore to identify a business key (in your case the name), ensure it is unique with a primary key and use that to determine if a a row needs to be inserted in the database.

Your code would look similar to this

if (productTypeRepository.existsByName(""FINISH PRODUCT")) {
    ProductType fp = new ProductType();
    fp.setName("FINISH PRODUCT");
    productTypeRepository.save(fp);
}
Related