ebean unidirectional @OneToOne relation with unique constraint

北城以北 提交于 2019-12-22 05:57:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15260116/ebean-unidirectional-onetoone-relation-with-unique-constraint

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