Error duplicate key when insert via API POST - java

i have a BD on PostgreSQL and i have many tables, but my problem is at table Usuario.
I create the table with this script:
CREATE SEQUENCE usuario_id_seq;
CREATE TABLE public.usuario
(
id BIGINT NOT NULL DEFAULT nextval ('usuario_id_seq'::regclass),
administrador BOOLEAN NULL,
password CHARACTER VARYING (20) NOT NULL,
username CHARACTER VARYING (40) NOT NULL,
CONSTRAINT usuario_pkey PRIMARY KEY (id)
NOT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT uk_863n1y3x0jalatoir4325ehal UNIQUE (username)
NOT DEFERRABLE INITIALLY IMMEDIATE
);
And I insert one user with:
Insert into usuario (username, password, administrador) values ('prueba', '1234', false);
This goes ok, now i have on Spring-boot this:
#Entity
#Table(name = "usuario")
public class Usuario implements Serializable {
#Id
#GeneratedValue
private Long id;
#NotNull
#Size(max = 40)
#Column(name = "username", unique = true)
private String username;
#NotNull
#Size(max = 20)
#Column(name = "password")
private String password;
#Column(name = "administrador")
private boolean administrador;
#ManyToMany(cascade = {
CascadeType.ALL
})
#JoinTable(name = "usuario_alerta",
joinColumns = {#JoinColumn(name = "id_usuario", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "id_alerta", referencedColumnName = "id")})
private Set<Alerta> alertasUsuario;
#ManyToMany(cascade = {
CascadeType.ALL
})
#JoinTable(name = "usuario_producto",
joinColumns = {#JoinColumn(name = "id_usuario", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "id_producto", referencedColumnName = "id")})
private Set<Producto> productosUsuario;
// Hibernate requires a no-arg constructor
public Usuario() {
}
public Usuario(String username, String password, boolean administrador) {
this.username = username;
this.password = password;
this.administrador = administrador;
}
..... Getters and Setters
Now, when i try to insert into table Usuario using API, calling to this:
#PostMapping("/usuario")
ResponseEntity<Usuario> newUser(#ModelAttribute Usuario usuario) {
Usuario user = usuarioRepository.save(usuario);
if(user != null)
return new ResponseEntity<Usuario>(user, HttpStatus.CREATED);
return new ResponseEntity<Usuario>(user, HttpStatus.BAD_REQUEST);
}
I get the error:
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "usuario_pkey" Detail: Key (id)=(1) already exists.
And this is because i create the user with id=1 ont the init script.
Who can i insert into a table using SQL and after using Spring-boot without get this error?

Ok, i saw that #GeneratedValue has a atribute generator so I just try to add the sequence generator that i had created before and it works. So, the solution was put this line like:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator="usuario_id_seq")
private Long id;

Related

JPA #JoinTable with composite (2 column) primary keys

In a spring-boot app, I've got the following entity definition:
#Data
#Entity
#Table(name = "users")
public class User {
#Id
#Column(nullable = false, name = "username", length = 100)
private String username;
#JoinTable(name = "userrole",
joinColumns = { #JoinColumn(name = "username") },
inverseJoinColumns = { #JoinColumn(name = "role") }
)
#OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Role> roles;`
I'm using Spring-data-jpa,Hibernate with H2 as the database.
The trouble is that spring-data-jpa, hibernate always generate/creates the join table (DDL) 'userrole' with a single column primary key. e.g. 'username'.
Hence, if records such as {'username', 'user_role'} and {'username', 'admin_role'} is inserted in the join table ('userrole'), the next insert fails with an error due to the 'duplicate' primary key.
I've tried using both columns in the above definition, as well as the following variation:
#OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JoinColumns({
#JoinColumn(name = "username"),
#JoinColumn(name = "role") })
private List<Role> roles;`
But that they resulted in the same or worse problems, e.g. and in the latter, even table creation fails because only a single column is used as primary key for the jointable. Role is simply another table with 2 columns 'role' and 'description', basically a role catalog.
How do we specify to JPA that the #JoinTable should use both 'username' and 'role' columns as composite primary keys?
edit:
I tried using an independent table/entity as suggested, thanks #Kamil Bęben
#Data
#Entity
#Table(name = "users")
public class User {
#Id
#Column(nullable = false, name = "username", length = 100)
private String username;
#OneToMany(
fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
mappedBy = "username",
orphanRemoval = true
)
#ElementCollection
private List<UserRole> roles;
UserRole is defined as such
#Data
#NoArgsConstructor
#Entity
#Table(name = "userrole")
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userrole_seq")
Long id;
#Column(nullable = false, name = "username", length = 100)
private String username;
#Column(nullable = false, name = "role", length = 50)
private String role;
the repository for that user-roles join table is defined as
#Repository
public interface UserRoleRepository extends CrudRepository<UserRole, Long> {
UserRole findByUsernameAndRole(String username, String role);
List<UserRole> findByUsername(String username);
List<UserRole> findByRole(String role);
}
Admittedly, ugly, but that it works. And that somehow, it seemed to use the correct findByUsername() method to retrieve the roles as is relevant to the user, probably related to the 'mappedBy' clause. 'black magic'! There's lots more that I'd still need to find my way around JPA, Spring, Spring-data
edit2:
further update:
the original #JoinTable works as well.
But that the relations need to be specified as #ManyToMany
#ManyToMany(
fetch = FetchType.EAGER,
cascade = CascadeType.MERGE
)
#JoinTable(name = "usersroles",
joinColumns = { #JoinColumn(name = "username") },
inverseJoinColumns = { #JoinColumn(name = "role") }
)
private List<Role> roles = new ArrayList<Role>();
This creates 2 column primary keys as expected for the 'users-roles' table
Thanks to #Roman
If Role only has two columns, eg user_id and role, the way to map this in jpa would be as following
#ElementCollection
#CollectionTable(name = "user_roles", joinColumns = #JoinColumn(name = "user_id"))
#Column(name = "role")
List<String> roles = new ArrayList<>();
Otherwise, jpa really requires each entity's identifier and join columns to be separate columns, so Role entity would have to have columns like id, user_id and role_name. Could look like this .:
class Role {
#Id
Long id;
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "id");
User user;
String roleName;
// Other fields
}
And in the User entity
#OneToMany(mappedBy = "user") // user is Field's name, not a column
List<Role> roles = new ArrayList<>();
Further reading

Repeated column in mapping for entity in #OneToOne

I have two tables:
CREATE TABLE users
(
id INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(68) NOT NULL,
oldPassword VARCHAR(68),
enabled BOOLEAN NOT NULL
);
and
CREATE TABLE authorities (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
);
CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority);
Unfortunatelly instead of joining with authority_id which should be in users table I just have username which is the same in both tables.
In models I tried (ommited getters and setters):
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String oldPassword;
private boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "username", referencedColumnName = "username")
private Authorities authority;
}
and
#Entity
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String authority;
#OneToOne(mappedBy = "authority")
private User user;
}
but then I have an error: Repeated column in mapping for entity column: username (should be mapped with insert="false" update="false")
The reason you are getting usernames in both tables is that you have declared username column in both the tables.
Also, you have to map the relation based on the authority_id so the code of the models would look like this:
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String oldPassword;
private boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "authority_id", referencedColumnName = "id")
private Authorities authority;
}
#Entity
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String authority;
#OneToOne(mappedBy = "authority")
private User user;
}
And the tables will be created like this:
Hope this solves your problem.
The message is clear: you have a repeated column in the mapping, and a column "username" in both tables has repeated. Instead of this, you should use this :
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "authority_username", referencedColumnName = "username")
private Authorities authority;

Why does JpaRepository while saving entity tried to create entity for null FK key?

I have Person table with field country in it (FK, can be null).
When I try to save Person with empty country value, I'll get an error 500 and message
2020-01-30 15:16:37.277 WARN 10524 --- [nio-8098-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2020-01-30 15:16:37.277 ERROR 10524 --- [nio-8098-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ОШИБКА: нулевое значение в столбце "code" нарушает ограничение NOT NULL
Подробности: Ошибочная строка содержит (42, null, null, null).
2020-01-30 15:16:37.299 ERROR 10524 --- [nio-8098-exec-1] o.z.problem.spring.common.AdviceTraits : Internal Server Error
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
Rough error traduction:
Error: null value in "code" column breaks NOT NULL restriction Details: The error string contains (42, null, null, null).
Person.java
#Entity
#Table(name = "t_person")
#Data
public class Person {
#Id
#Column(name = "person_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String surname;
private String name;
private String patronymic;
#Column(name = "surname_rus")
private String surnameRus;
#Column(name = "name_rus")
private String nameRus;
#Column(name = "surname_eng")
private String surnameEng;
#Column(name = "name_eng")
private String nameEng;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "country_id")
private Country country;
private String settlement;
private String occupation;
#ManyToMany
#JoinTable(
name = "person_link",
joinColumns = #JoinColumn(name = "person_id", referencedColumnName = "person_id"),
inverseJoinColumns = #JoinColumn(name = "link_id", referencedColumnName = "link_id"))
private List<UrlLink> linkList;
#ManyToMany
#JoinTable(
name = "org_actor",
joinColumns = #JoinColumn(name = "actor_id", referencedColumnName = "person_id"),
inverseJoinColumns = #JoinColumn(name = "org_id", referencedColumnName = "org_id"))
private List<Org> orgList;
private String description;
#ManyToMany
#JoinTable(
name = "person_hashtag",
joinColumns = #JoinColumn(name = "person_id", referencedColumnName = "person_id"),
inverseJoinColumns = #JoinColumn(name = "hashtag_id", referencedColumnName = "hashtag_id"))
private List<HashTag> hashtagList;
************
Country.java
#Entity
#Table(name="t_country")
#Data
public class Country {
#Id
#Column(name = "country_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String code;
private String name;
}
create table t_country
(
country_id serial not null
constraint t_country_pkey
primary key,
code char(3) not null
constraint unique_constr_code
unique,
name text
constraint unique_constr_name
unique,
miscellany text,
constraint constr_name
unique (code, name)
);
How to save Person entity with empty country?
In your country db table definition the field code is defined as
code
char(3) not null
constraint unique_constr_code
unique,
means that there is a not null constraint on db level.
That's why you can not save a person with a country with empty fields.
So even though you do not have a not null constraint in the java code, the db rejects the value. Maybe you forgot to migrate your db after removing the not null constraint in your java code?

Exclude table using CrudRepository in Java

i have two tables Person and PersonType and there is a relation "ManyToMany" between these tables. During loading my application i am getting all the PersonTypes, but when i create new Person, i have an exception
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "person_type_person_type_name_key"
Detail: Key (person_type_name)=(TYPE1) already exists.
person_type_person_type_name_key is my table where i should store the relations between Person and PersonType. When i create a new Person i DO NOT want to insert into PersonType table because the person type already exists. What should i do, not to insert into DB ? I am using personService.save(person); which is trying to insert also in person_type table into DB.
#Table(name = "person")
public class Person {
#Id
#Column(name = "id")
#GeneratedValue(generator = "person_id_seq")
#SequenceGenerator(sequenceName = "person_id_seq", name = "person_id_seq", schema = "manager", allocationSize = 1, initialValue = 1)
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "password")
private String password;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(
name = "person_person_types",
joinColumns = #JoinColumn(name = "person_fk"),
inverseJoinColumns = #JoinColumn(name = "person_type_fk"))
private List<PersonType> personTypes;
}
#Entity
#Table(name = "person_type")
public class PersonType {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "person_type_name", unique=true)
private String personType;
#ManyToMany(mappedBy = "personTypes", cascade = {CascadeType.ALL})
private Set<Person> persons;
}```
Maybe the problem is with inserting the PersonType. Ensure that you put PersonType with the same ID and same name into the DB. Also change CascadeType.ALL to be CascadeType.MERGE

Spring Data JPA saving two entities at the same time, null value in column "user_id"

I have users in my application and users have work details, I use one method to set the user/work details data and then I either add a new user or modify an existing one.
This is the method for setting user/work data:
public WorkDetail setWorkerData(PatchWorkerRequest request, User user, WorkDetail workDetail) {
if (request.getName() != null) {
user.setName(request.getName());
}
if (request.getIdCode() != null) {
user.setIdCode(request.getIdCode());
}
if (request.getEmail() != null) {
user.setEmail(request.getEmail());
}
if (request.getPhone() != null) {
user.setPhone(request.getPhone());
}
if (request.getAddress() != null) {
user.setAddress(request.getAddress());
}
if (request.getSignatureLevel() != null) {
user.setSignatureLevel(request.getSignatureLevel());
}
if (request.getAltContactRelation() != null) {
user.setAltContactRelation(request.getAltContactRelation());
}
if (request.getAltContactPhone() != null) {
user.setAltContactPhone(request.getAltContactPhone());
}
if (request.getRoles() != null) {
user.setRoles(request.getRoles());
}
if (request.getStatus() != null) {
user.setStatus(request.getStatus());
}
// Work details
if (request.getJobRelation() != null) {
workDetail.setJobRelation(request.getJobRelation());
}
if (request.getSalary() != null) {
workDetail.setSalary(request.getSalary());
}
if (request.getDistricts() != null) {
workDetail.setDistricts(request.getDistricts());
}
if (request.getCompetences() != null) {
workDetail.setCompetences(request.getCompetences());
}
workDetail.setUser(user);
user.setWorkDetail(workDetail);
return workDetailRepository.save(workDetail);
}
Now, modifying an existing worker works fine with this code:
public WorkDetail modifyWorker(Long workerId, PatchWorkerRequest request) {
WorkDetail workDetail = this.getWorkDetailById(workerId);
User user = userService.getUserById(workDetail.getUser().getId());
return setWorkerData(request, user, workDetail);
}
But when I try to create a new user/worker I get an error that "null value in column "user_id" violates not-null constraint". I assume it's because the workDetail and user don't get connected properly.
This is the method for creating a new worker:
public WorkDetail createWorker(PatchWorkerRequest request) {
WorkDetail workDetail = new WorkDetail();
User user = new User();
String generatedPassword = userService.generatePassword(8);
user.setPassword(passwordEncoder.encode(generatedPassword));
emailService.sendMail("SYDA", new String[]{request.getEmail()},
"Project SYDA",
"New password: " + generatedPassword + ".);
return setWorkerData(request, user, workDetail);
}
Also, is there any way I could send the email after saving the user so in case of errors it wouldn't send the email?
Entities:
User:
#Entity
#Data
#NoArgsConstructor
#TypeDefs({
#TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
})
#Table(name = "user_acc")
public class User implements Serializable {
#Id
#Column(unique = true, nullable = false, columnDefinition = "serial")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "id_code")
private BigInteger idCode;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "address")
private String address;
#Column(name = "phone")
private BigInteger phone;
#Column(name = "alt_contact_relation")
private String altContactRelation;
#Column(name = "alt_contact_phone")
private BigInteger altContactPhone;
#Column(name = "password", nullable = false)
#JsonIgnore
private String password;
#JsonIgnore
#Column(name = "create_time", nullable = false, updatable = false)
private Date createTime = new Date();
#JsonIgnore
#Column(name = "update_time", nullable = false)
private Date updateTime = new Date();
#Column(name = "status", nullable = false, columnDefinition = "active_status")
#Enumerated(EnumType.STRING)
#Type(type = "pgsql_enum")
private UserStatus status;
#OneToOne
#PrimaryKeyJoinColumn
#JsonIgnore
private WorkDetail workDetail;
#OneToMany(mappedBy = "user")
private List<UserFile> userFiles = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "signature_level_id")
private SignatureLevel signatureLevel;
#ManyToMany(fetch = FetchType.EAGER, targetEntity = UserRole.class)
#JoinTable(name = "user_has_user_role",
joinColumns = { #JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name = "user_role_id", referencedColumnName = "id")}
)
private Set<UserRole> roles = new HashSet<>();
#ManyToMany(fetch = FetchType.EAGER, targetEntity = Mechanism.class)
#JoinTable(name = "user_has_mechanism",
joinColumns = { #JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name = "mechanism_id", referencedColumnName = "id")}
)
private Set<Mechanism> mechanisms = new HashSet<>();
#ManyToMany(fetch = FetchType.EAGER, targetEntity = Service.class)
#JoinTable(name = "user_has_service",
joinColumns = { #JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name = "service_id", referencedColumnName = "id")}
)
private Set<Service> services = new HashSet<>();
#PreUpdate
#PrePersist
public void onCreateOnUpdate() {
updateTime = new Date();
}
public enum UserStatus {
active, temporarily_inactive, inactive
}
}
WorkDetail:
#Entity
#Data
#Table(name = "work_detail")
public class WorkDetail {
#Id
#Column(unique = true, nullable = false, columnDefinition = "serial")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "salary")
private float salary;
#OneToOne(mappedBy = "workDetail",fetch = FetchType.LAZY, optional = true)
#PrimaryKeyJoinColumn
private User user;
#Column(name = "create_time", nullable = false, updatable = false)
#JsonIgnore
private Date createTime = new Date();
#Column(name = "update_time", nullable = false)
#JsonIgnore
private Date updateTime = new Date();
#OneToMany(cascade = CascadeType.ALL, mappedBy = "workDetail")
private List<UserLeave> userLeaves = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "job_relation_id")
private JobRelation jobRelation;
#ManyToMany(fetch = FetchType.EAGER, targetEntity = District.class)
#JoinTable(name = "work_detail_has_district",
joinColumns = { #JoinColumn(name = "work_detail_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name = "district_id", referencedColumnName = "id")}
)
private Set<District> districts = new HashSet<>();
#ManyToMany(fetch = FetchType.EAGER, targetEntity = Competence.class)
#JoinTable(name = "work_detail_has_competence",
joinColumns = { #JoinColumn(name = "work_detail_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name = "competence_id", referencedColumnName = "id")}
)
private Set<Competence> competences = new HashSet<>();
#PreUpdate
#PrePersist
public void onCreateOnUpdate() {
updateTime = new Date();
}
}
Db tables:
-----------------------
-- User table
-----------------------
CREATE TABLE IF NOT EXISTS user_acc (
id SERIAL NOT NULL PRIMARY KEY,
name text NOT NULL,
id_code numeric NOT NULL,
email text NOT NULL UNIQUE,
address text NULL,
alt_contact_relation text NULL,
alt_contact_phone numeric NULL,
signature_level_id integer NULL,
username text NOT NULL,
password text NOT NULL,
create_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
update_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
status active_status NOT NULL DEFAULT 'active',
CONSTRAINT FK_user_signature_level FOREIGN KEY (signature_level_id) REFERENCES signature_level (id)
ON DELETE NO ACTION ON UPDATE NO ACTION
);
-----------------------
-- User: work detail table
-----------------------
CREATE TABLE IF NOT EXISTS work_detail (
id SERIAL NOT NULL PRIMARY KEY,
salary decimal NULL,
job_relation_id integer NOT NULL,
user_id integer NOT NULL,
create_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
update_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
CONSTRAINT FK_work_detail_user FOREIGN KEY (user_id) REFERENCES user_acc (id)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_work_details_job_relations1 FOREIGN KEY (job_relation_id)
REFERENCES job_relation (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
You need to save the user before you add it to the workDetail. The new User object does not have an id, and that is why you are getting that exception.
Something like this:
public WorkDetail createWorker(PatchWorkerRequest request) {
WorkDetail workDetail = new WorkDetail();
User user = new User();
String generatedPassword = userService.generatePassword(8);
user.setPassword(passwordEncoder.encode(generatedPassword));
user = userRepository.save(user);
emailService.sendMail("SYDA", new String[]{request.getEmail()},
"Project SYDA",
"New password: " + generatedPassword + ".);
return setWorkerData(request, user, workDetail);
}
or you can add a saveUser call inside the setWorkerData method.
...
if (request.getStatus() != null) {
user.setStatus(request.getStatus());
}
user = userRepository.save(user);
...
In your setWorker() method you try to set user for workDetail Object but user Object doesn't have their user_id because this user object is detached mode and still no user_id is associated with user Object.
//some code in your setWorker() Method.
workDetail.setUser(user); //you try to set a detached User Object which doesn't have it's id.
user.setWorkDetail(workDetail);
return workDetailRepository.save(workDetail);
So, either save that user just before setting and make sure user Object is persisted into database .
add this line before above code..
user = userRepository.save(user); // add this line....
workDetail.setUser(user); //now your User Object will have it's id.
user.setWorkDetail(workDetail);
return workDetailRepository.save(workDetail);
there is also a another way to perform this without calling save() method just by using the concept of cascading for more info go through with this Link Here
You can use the spring-boot-starter-mail dependency to get this work
It means the user object is not saved when you try to save the workdetail object.
So there is not user_id to put, hence the null value.
Could should post you entities please ? (specially the mapping between them).
I think, you should have something like #OneToOne(cascade = CascadeType.PERSIST) if you want you save both entities at the same time.
Your mapping is wrong.
Here's what you should do :
in WorkDetail :
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private User user;
in User :
#OneToOne(mappedBy = "user")
#JsonIgnore
private WorkDetail workDetail;

Categories