spring-boot-starter-parent 2.4.1
spring-boot-starter-data-jpa
postgres 12.5
A short excerpt from an entity:
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
public class Branch extends BaseEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(columnDefinition = "varchar(255) default ''", nullable = false)
private String name;
@Column(columnDefinition = "varchar(255) default ''")
private String segmentFour;
}
The entity generates a table like this:
This is it:
ads=# \d clients__branch
Table "public.clients__branch"
Column | Type | Collation | Nullable | Default
-----------------------+------------------------+-----------+----------+----------------------------------
id | integer | | not null | generated by default as identity
name | character varying(255) | | not null | ''::character varying
segment_four | character varying(255) | | | ''::character varying
We can see that:
- "name" is not null and has a default value ''.
- "segment_one" has a default value, but there is no not null constraint.
Let's try to use this.
Let's fill the data and save it:
Branch branch0 = new Branch();
branch0.setName("Train");
branch0.setSegmentFour("");
Branch branch1 = new Branch();
branch1.setName("Car");
branch1.setSegmentFour(null);
Branch branch2 = new Branch();
branch2.setName("Ship");
Result:
ads=# select id, name, case when segment_four is null then 'null' when segment_four = '' then 'space' end as segment from clients__branch;
id | name | segment
----+---------+---------
1 | Vosst | space
2 | Ryba | null
3 | Admiral | null
Problems
I'd like to prevent anybody to from setting Null as in case with branch1.
If I organize it like this:
@Column(columnDefinition = "varchar(255) default ''", nullable = false) private String segmentFour;
then I get:
ERROR: null value in column "segment_four" violates not-null constraint
I'd like to have a default value (the code for branch2 should generate '' in the segment_four).
Could you help me?