![](/img/trans.png)
[英]Spring data JPA does not allow an Entity to be peristed if the primary key is not null
[英]Spring Data JPA - saving a new entity with custom id / primary key
簡而言之,我的問題是如何使用Spring數據JPA保存具有預設主鍵(而不是null)的實體。
要解釋一下,請考慮一個名為Customer
的簡單實體類。 請記住,id未設置為自動增量,並且必須是自定義唯一值。 這只是一個小例子。 我需要在我的實際表中的id是一個自定義的唯一的,像用戶名。
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "cust_id", nullable = false)
private Integer custId;
@Column(name = "first_name", length = 30)
private String firstName;
@Column(name = "last_name", length = 30)
private String lastName;
//getter, setters
}
而且,我有一個CustomerRepository
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
}
現在,我想我必須插入一個id為101的新客戶記錄。預期的方法是:
Customer customer = new Customer();
customer.setCustId(101);
customer.setFirstName("Some");
customer.setLastName("Name");
repository.save(customer);
但是,它發生了repository.save()
沒有插入id為101的新客戶。那么,我該怎么做呢?
如果您處於活動事務中,請始終記住顯式調用flush或確保事務已提交,然后單獨檢查數據庫以確保已進行更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.