[英]ActiveJDBC: save() generates insert only for auto-generated primary key?
I recently started using ActiveJDBC. 我最近开始使用ActiveJDBC。 I have the following table (postgresql) 我有下表(PostgreSQL)
CREATE TABLE users (
id uuid PRIMARY KEY,
email text UNIQUE NOT NULL,
password text,
<some more nullable columns>
created_at timestamp with time zone NOT NULL default (now() at time zone 'utc'),
updated_at timestamp with time zone
);
As you can see, the primary key is of type uuid and has no auto-generate value of any kind. 如您所见,主键的类型为uuid,没有任何类型的自动生成值。
This is my User class which models the table : 这是我的表的用户类:
public class User extends Model
{
public User() {
setId(UUID.randomUUID()); // sets value to primary key
}
...
}
This is my attempt to create a new row and insert it : 这是我尝试创建新行并将其插入的尝试:
User u = new User();
System.out.println(u.saveIt());
actually, I expected the insert to fail, since I did not set any value for mandatory email column. 实际上,我期望插入操作失败,因为我没有为强制性电子邮件列设置任何值。 However, simply got false as return value. 但是,仅将false作为返回值。 when I turned on logging, I saw that the framework generated an update sql instead of insert: 当我打开日志记录时,我看到框架生成了一个更新sql而不是insert:
[main] INFO org.javalite.activejdbc.DB - Query: "UPDATE users SET email = ?, ..., updated_at = ? WHERE id = ?", with parameters: <null>, <null>, <null>, <null>, <null>, <null>, <null>, <2016-01-07 17:30:46.025>, <0621fbdb-5b95-4ee7-a474-8ee9165e2982>, took: 1 milliseconds
so I looked at the save()
method inside org.javalite.activejdbc.Model
class and saw this piece of code: 因此,我查看了org.javalite.activejdbc.Model
类中的save()
方法,并看到了这段代码:
if (getId() == null) {
result = insert();
} else {
result = update();
}
does this mean that id column has to be empty in order for an insert to be generated ? 这是否意味着id列必须为空才能生成插入? if this is true this is unacceptable, so I must be missing something. 如果是这样,那是不可接受的,因此我必须缺少一些东西。
@sharonbn, please, see this documentation page: http://javalite.io/surrogate_primary_keys . @sharonbn,请参阅此文档页面: http ://javalite.io/surrogate_primary_keys。 ActiveJDBC depends on autogenerated IDs. ActiveJDBC取决于自动生成的ID。 If the ID == null, the frameworks assumes this is a new record, and generates INSERT statement. 如果ID == null,则框架将假定这是一条新记录,并生成INSERT语句。 If it is non-null, it is assumed the record already exists, and generates UPDATE. 如果非空,则假定记录已存在,并生成UPDATE。
In your case, you will need to explicitly call user.insert()
instead of user.saveIt()
. 在您的情况下,您将需要显式调用user.insert()
而不是user.saveIt()
。 This is an 'expert' mode in cases when developers want to be in control of ID management. 当开发人员希望控制ID管理时,这是一种“专家”模式。 Further, the method user.update()
is private. 此外,方法user.update()
是私有的。 So for you to insert a new record, you will be calling 因此,为您插入新记录,您将打电话给
user.insert();
and for updates: 和更新:
user.save(); // or: user.saveIt();
, depending on what you want. ,具体取决于您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.