JPA / Spring-boot密钥“ PRIMARY”的重复条目

时间:2018-10-31 08:32:44

标签: mysql spring-boot jpa spring-data-jpa

我将JPA用于mysql操作,但是几次我通过JPA执行mysql保存操作时出错。 执行保存操作时出错=>

  

无法打开JPA EntityManager进行事务;键“ PRIMARY”的条目重复

表模型类:

@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架构:

 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
public interface TableXRepository extends CrudRepository<tableX,Long> {
}

Mysql操作类:

@Component
@Transactional
public class tableXoperationImpl implements ItableXoperation {

    @Autowired
    private TableXRepository tableXRepository;

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

什么都可以,我在这里不见了,我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

我认为您的列product_id实际上在表中被定义为主键。

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

您可以自己分配productId,也可以分配 Id生成策略 Primary Key Id Generation Strategy Type

如果您决定自己分配productId,则它必须是唯一的(该表(产品)的该列中不存在)。

如果您仔细查看异常,则会发现Duplicate entry for key 'PRIMARY',这意味着尝试在表(Product)的主键列(product_id)中插入重复的值。

或者您可以将上面的主键列代码替换为此

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

谢谢:)

答案 1 :(得分:0)

请在productId上使用@GeneratedValue(strategy = GenerationType.AUTO)。

相关问题