Amit Kumar
Amit Kumar

Reputation: 63

JPA/Spring-boot Duplicate entry for key 'PRIMARY'

I am using JPA for mysql operations, but the few times I am getting error while performing mysql save operations through JPA. Error while performing save operation =>

Could not open JPA EntityManager for transaction; Duplicate entry for key 'PRIMARY'

Table Model Class:

@Entity
@Table(name="table_x")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
@TypeDefs({
        @TypeDef(name = "json", typeClass = JsonStringType.class),
        @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class),
})
public class tableX implements Serializable {

    @Id
    @Column(name="product_id")
    private Long productId;

    @Column(name="parent_id")
    private Long parentId;

    // other fields
}

Mysql Schema:

 CREATE TABLE `table_x` (
  `product_id` int(12) unsigned NOT NULL,
  `parent_id` int(12) unsigned DEFAULT NULL,
  // other fields
  PRIMARY KEY (`product_id`)
)

Repository Class:

@Repository
public interface TableXRepository extends CrudRepository<tableX,Long> {
}

Mysql Operation Class:

@Component
@Transactional
public class tableXoperationImpl implements ItableXoperation {

    @Autowired
    private TableXRepository tableXRepository;

    public void save(tableX data) {
        tableXRepository.save(data);
    }
}

is anything, I am missing here, any help will be appreciated.

Upvotes: 5

Views: 20516

Answers (3)

eeqk
eeqk

Reputation: 3862

In my case I inserted data from a CSV and hibernate_sequence got out of sync which caused problems with save/saveAll.

Just edit the hibernate_sequence to the latest id+1 and it should work

Upvotes: 0

Chirdeep Tomar
Chirdeep Tomar

Reputation: 4461

Please use the @GeneratedValue(strategy = GenerationType.AUTO) on productId.

Upvotes: 2

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

I think problem with your column product_id which actually defined as primary key in table.

@Id  //this annotation make column as primary key.
@Column(name="product_id")
private Long productId;

You can assign productId either by yourself or assign a Id Generation Strategy Primary Key Id Generation Strategy Type.

if you decide to assign productId by yourself then it must be unique (not exists in that column in that table (product)).

If you look your exception closely you will find this out Duplicate entry for key 'PRIMARY' , Which means try to insert duplicate value in primary key column (product_id) of table (Product).

or you may replace above primary key column code with this

@GeneratedValue(strategy=GenerationType.AUTO) // automatically generated primary key.
@Id  // Primary key.
@Column(name="product_id")
private Long productId;

Thanks :)

Upvotes: 0

Related Questions