我有一个指向postgresql表的实体类。下面是表结构。 Paymentreferencenumber是由触发器填充的PK。 id字段是序列生成的字段。当我尝试使用JPARepository保存方法保存在此表中时,它将插入第一条记录。但是之后,由于主键约束,它失败了。由于PK是字符串类型并使用触发器生成,因此我将生成器策略指定为“选择”。任何人都可以帮我解决这个障碍,并指出正确的方向。谢谢
表结构-
custId serial not null,
paymentreferencenumber varchar(32) not null
constraint customers1_pkey
primary key,
firstname varchar(255),
lastname varchar(255)
Entity class --
@Entity
@Table(name = "customersnew")
public class Customer implements Serializable {
private static final long serialVersionUID = -1L;
@GeneratedValue(generator = "seq")
@GenericGenerator(name="seq", strategy="sequence", parameters = { @Parameter(name="key", value = "customersnew_custid_seq")})
@Column(name = "custid")
private long id;
@Id
@GeneratedValue(generator = "trigger_generated")
@GenericGenerator(name="trigger_generated", strategy="select", parameters = { @Parameter(name="key", value = "id")})
@Column(name = "paymentreferencenumber")
private String refNum;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String lastName;
}
--- Controller using JPA save
@RestController
public class CustomerController {
@Autowired
CustomerRepository repository;
EntityManagerFactory emf;
public CustomerController(CustomerRepository repository, EntityManagerFactory emf) {
this.repository = repository;
this.emf = emf;
}
@PostMapping("/create")
public String create(@RequestBody CustomerUI customer){
// save a single Customer
Customer returnObj = repository.saveAndFlush(new Customer(customer.getFirstName(), customer.getLastName()));
PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
Object retObj = util.getIdentifier(returnObj);
return "Customer is created";
}
答案 0 :(得分:0)
如果您未指定ID生成策略,则Hibernate将使用GenerationType.AUTO
。这将导致
AUTO-标识列,序列或表,具体取决于 基础数据库。
如果您查看here,您会注意到所有生成long
,short
或int
类型而不是String
类型的ID的人。
假设您想要一个String
UUID作为ID,则可以使用
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "paymentreferencenumber")
private String refNum;