janusz j
janusz j

Reputation: 329

JPA repository read, delete and save Object with old id

I am trying to read Pricebject ID from repository, delete it and save it as new PriceObject again with old ID, but it saves with different ID.

This is my method:

public void getActualPricesAndSaveInDb() {

        try {
                String symbolString = symbol.getSymbol();
                PriceObject oldPriceObject = pricesRepository.findByCompanySymbol(symbolString);
                PriceObject newPriceObject = new PriceObject();
                if (oldPriceObject != null) {
                    pricesRepository.deleteByCompanySymbol(symbolString); 
                    newPriceObject.setId(oldPriceObject.getId());
                }
                newPriceObject.setCompanySymbol(symbolString);
                pricesRepository.save(newPriceObject);
        } catch (APICommandConstructionException | APIReplyParseException | APICommunicationException
                | APIErrorResponse e) {
            e.printStackTrace();
        }
    }

This is my PriceObject.class:

@Entity
@Data
public class PriceObject {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    Integer id;

    @Column(nullable = false)
    String companySymbol;

    ...
}

I've tried so far:

  • change annotation @GeneratedValue parameter for (strategy = GenerationType.AUTO),

  • change annotation @GeneratedValue parameter for (strategy = GenerationType.SEQUENCE).

Upvotes: 1

Views: 1351

Answers (2)

b.GHILAS
b.GHILAS

Reputation: 2303

Setting the id directly using the entity won't work if you specify a strategy for generating the id. To set the id of the entity you want you have two solution (not all possible solution by the way):

  1. Remove the @GeneratedValue annotation from your id field, but if you do this you have to supply an id for each entity you want to save.
  2. Create a native query directly using the EntityManager.

    entityManager.createNativeQuery("insert into table(id, ...) values (id,...)");

Upvotes: 3

Sara
Sara

Reputation: 41

I'm not sure I'm understanding your problem correctly but it might be due to the generated value. Maybe you could try deleting that annotation if you don't need it for any other method, or changing it with this one: @Column(unique = true).

Upvotes: 1

Related Questions