ebean unidirectional @OneToOne relation with unique constraint

寵の児 提交于 2019-12-05 10:13:21
Wayan Wiprayoga

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 surround Model.save() or form.get().save() expression (saving-the-model) with try-catch block to handle the PersistenceException.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!