Ebean unidirectional @OneToOne relationship with unique constraint

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 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 user_id is unique inside the Drivers table. But the above code does not provide this. (I can create several drivers with the same user ID).

Ideally, I do not want to add @OneToOne relationships to the User class, because in my application there are several different roles (for example, driver, teacher, agent, etc.), and I do not want to pollute the user class with all these relationships.

How can i achieve this?

+4
source share
1 answer

I tried this code for the model for me and it worked. It should be noted that you must use the @OneToOne annotation @OneToOne that ORM knows that you have a foreign key reference to another model.

The model is as follows:

 @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 an evolution of the script as follows:

 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 have a unique user link in the driver table.


Additional Information

Since there is an additional restriction that is not handled by the framework, but with databases applied to the model (for example, the unique constraint), you can surround Model.save() or form.get().save() to check the input or handle the exception that has form.get().save() (save-the-model) with a try-catch to handle a PersistenceException .

+3
source

All Articles