我创建了一个新表,该表在启动时通过FlywayDB进行迁移:
CREATE TABLE IF NOT EXISTS place_address (
id bigint,
place_id bigint NOT NULL,
street character varying(255) NOT NULL,
postal_code character varying(255) NOT NULL,
city character varying(255) NOT NULL,
country character varying(255) NOT NULL,
address_type character varying(255) NOT NULL,
FOREIGN KEY (place_id) REFERENCES place(id),
CONSTRAINT place_address_pkey PRIMARY KEY (id)
);
我正在创建这样的实体,并将其存储在JpaRepository
中:
PlaceAddressEntity placeAddressEntity = new PlaceAddressEntity();
placeAddressEntity.setPlace(placeEntity);
placeAddressEntity.setStreet(establishmentDto.getAddress().getStreet());
placeAddressEntity.setCity(establishmentDto.getAddress().getCity());
placeAddressEntity.setCountry(establishmentDto.getAddress().getCountry());
placeAddressEntity.setPostalCode(establishmentDto.getAddress().getPostalCode());
placeAddressEntity.setAddressType(AddressType.GEOGRAPHIC);
this.placeAddessRepository.save(placeAddressEntity);
但是,这就是我得到的:
2018-09-21 18:42:05.319 WARN 13842 --- [io-8443-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2018-09-21 18:42:05.319 ERROR 13842 --- [io-8443-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "id" violates not-null constraint
Detail: Failing row contains (null, 8, Western Road 2-20, NW10 7LW, Greater London, United Kingdom, GEOGRAPHIC).
2018-09-21 18:42:05.322 INFO 13842 --- [io-8443-exec-10] m.a.s.e.CustomRestExceptionHandler : org.springframework.dao.DataIntegrityViolationException
2018-09-21 18:42:05.323 INFO 13842 --- [io-8443-exec-10] m.a.s.e.CustomRestExceptionHandler : org.hibernate.exception.ConstraintViolationException
该实体定义为:
@Entity
@Table(name = "place_address")
public class PlaceAddressEntity {
public enum AddressType {
GEOGRAPHIC,
BILLING
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "place_id", nullable = false)
private PlaceEntity place;
@Column
private String street;
@Column(name = "postal_code")
private String postalCode;
@Column
private String city;
@Column
private String country;
@Column(name = "address_type")
@Enumerated(EnumType.STRING)
private AddressType addressType;
}
我不知道问题出在哪里-我不知道我在想什么?
这里也是PlaceAddressRepository
:
public interface PlaceAddessRepository extends JpaRepository<PlaceAddressEntity, Long> {
}
答案 0 :(得分:1)
这是因为您没有使用自动增量功能
使用id SERIAL PRIMARY KEY
,必须在表定义中进行设置。
答案 1 :(得分:0)
我正要发布答案,因为我看到了@Antoniossss答案。但是,我发布了我的信息,以便我们可以看到SERIAL
,或者在我的情况下BIGSERIAL
为我们所做的事情。
我能够做到这一点:
CREATE SEQUENCE IF NOT EXISTS public.place_address_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER SEQUENCE public.place_address_id_seq OWNED BY public.place_address.id;
ALTER TABLE ONLY public.place_address ALTER COLUMN id SET DEFAULT nextval('public.place_address_id_seq'::regclass);
但是,我还是比较喜欢这种衬垫:
id BIGSERIAL PRIMARY KEY,