Ami*_*mar 5 mysql jpa spring-data-jpa spring-boot
我使用 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
}
Run Code Online (Sandbox Code Playgroud)
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`)
)
Run Code Online (Sandbox Code Playgroud)
存储库类:
@Repository
public interface TableXRepository extends CrudRepository<tableX,Long> {
}
Run Code Online (Sandbox Code Playgroud)
Mysql操作类:
@Component
@Transactional
public class tableXoperationImpl implements ItableXoperation {
@Autowired
private TableXRepository tableXRepository;
public void save(tableX data) {
tableXRepository.save(data);
}
}
Run Code Online (Sandbox Code Playgroud)
是什么,我在这里失踪了,任何帮助将不胜感激。
product_id我认为您的列实际上定义为表中的主键有问题。
@Id //this annotation make column as primary key.
@Column(name="product_id")
private Long productId;
Run Code Online (Sandbox Code Playgroud)
您可以productId自行分配或分配Id Generation Strategy 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;
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
| 归档时间: |
|
| 查看次数: |
18246 次 |
| 最近记录: |