I have a User class:
@Entity
public class User extends Model {
@Id
public Long id;
public String email;
public String name;
public String password;
}
and a driver class
@Entity
public class Driver extends Model {
@Id
public Long id;
@OneToOne (cascade = CascadeType.ALL)
@Column(unique = true)
public User user;
}
I want to make sure that the user_id is unique inside the Drivers table. But the code above does not enforce that. (I can create multiple drivers with the same user id).
Ideally, I do not want to add the @OneToOne relations in the User class because there are several different roles inside my app (e.g. driver, teacher, agent etc.) and I don't want to pollute user class with all those relations.
How can I achieve this?
I have tried this code on the model for me, and it worked. One thing to be noted, that you must use @OneToOne
annotation to let the ORM knows that you have foreign key reference to other model.
The model look like following:
@Entity
// add unique constraint to user_id column
@Table(name = "driver",
uniqueConstraints = @UniqueConstraint(columnNames = "user_id")
)
public class Driver extends Model {
@Id
public Long id;
@OneToOne
@JoinColumn(name = "user_id")
public User user;
}
It will generate evolution script like this :
create table driver (
id bigint not null,
user_id bigint,
constraint uq_driver_1 unique (user_id), # unique database constraint
constraint pk_driver primary key (id)
);
So, with this method you can make sure that you will have unique user
reference on driver
table.
Additional Info
Because there is an additional constraint, that is not handled by framework but by the database applied on the model (such as the
unique
constraint), to validate the input or handling the occurred exception, you can surroundModel.save()
orform.get().save()
expression (saving-the-model) withtry-catch
block to handle the PersistenceException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With