具有唯一约束的Bean单向@OneToOne关系 [英] ebean unidirectional @OneToOne relation with unique constraint

查看:121
本文介绍了具有唯一约束的Bean单向@OneToOne关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个User类:

@Entity
public class User extends Model {

@Id
public Long id;
public String email;
public String name;
public String password;
}

和驱动程序类

@Entity
public class Driver extends Model {
@Id
public Long id;

@OneToOne (cascade = CascadeType.ALL)
@Column(unique = true)
public User user;
}

我想确保user_id在Drivers表中是唯一的.但是上面的代码没有强制执行该操作. (我可以使用相同的用户ID创建多个驱动程序.)

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).

理想情况下,我不想在User类中添加@OneToOne关系,因为我的应用程序内部有几个不同的角色(例如,驱动程序,老师,代理等),并且我不想污染所有用户类这些关系.

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.

我该如何实现?

推荐答案

我已经为我在模型上尝试过此代码,并且可以正常工作.需要注意的一件事是,必须使用@OneToOne批注使ORM知道您具有对其他模型的外键引用.

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.

该模型如下所示:

@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)
);

因此,通过这种方法,您可以确保在driver表上具有唯一的user引用.

So, with this method you can make sure that you will have unique user reference on driver table.

其他信息

因为存在一个附加约束,该约束不是由框架处理而是由模型上应用的数据库(例如unique约束)来验证输入或处理发生的异常时,可以用try-catch块将Model.save()form.get().save()表达式(保存模型)包围起来,以处理 PersistenceException .

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.

这篇关于具有唯一约束的Bean单向@OneToOne关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆