Установка createdBy и updatedBy в объектах JPA автоматически

Если я понимаю правильно, необходимо быть в состоянии сделать то, что Вы хотите путем отбрасывания ограничения внешнего ключа, добавления нового (который расположится каскадом), делая материал, и воссоздавая ограничение внешнего ключа ограничения.

, Например:

testing=# create table a (id integer primary key);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "a_pkey" for table "a"
CREATE TABLE
testing=# create table b (id integer references a);
CREATE TABLE

-- put some data in the table
testing=# insert into a values(1);
INSERT 0 1
testing=# insert into a values(2);
INSERT 0 1
testing=# insert into b values(2);
INSERT 0 1
testing=# insert into b values(1);
INSERT 0 1

-- restricting works
testing=# delete from a where id=1;
ERROR:  update or delete on table "a" violates foreign key constraint "b_id_fkey" on table "b"
DETAIL:  Key (id)=(1) is still referenced from table "b".

-- find the name of the constraint
testing=# \d b;
       Table "public.b"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id)

-- drop the constraint
testing=# alter table b drop constraint b_a_id_fkey;
ALTER TABLE

-- create a cascading one
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade; 
ALTER TABLE

testing=# delete from a where id=1;
DELETE 1
testing=# select * from a;
 id 
----
  2
(1 row)

testing=# select * from b;
 id 
----
  2
(1 row)

-- it works, do your stuff.
-- [stuff]

-- recreate the previous state
testing=# \d b;
       Table "public.b"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE

testing=# alter table b drop constraint b_id_fkey;
ALTER TABLE
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict; 
ALTER TABLE

, Конечно, необходимо абстрагировать материал как этот в процедуру ради психического здоровья.

6
задан JMM 8 December 2009 в 07:51
поделиться

2 ответа

Вы можете взглянуть на один из этих подходов для передачи идентификатора пользователя в качестве контекста на бизнес-уровне:

(Сообщения могут быть актуальными, даже если вы не используете EJB. Второй пост имеет смысл, однако, только если вы используете Spring с JTA)

Я лично не рекомендую такой подход , поскольку я вижу две проблемы с этим:

  • Тестируемость: контекстные данные должны быть настроены в тесте
  • Контракт: контекстные данные участвуют в контракте для использования объекта, но не четко видны в интерфейсе.

Передача userID «повсюду» может показаться большой работой, но я думаю, что это чище.

Чтобы автоматически устанавливать дату и идентификатор пользователя при создании или обновлении объекта, Надеюсь, это поможет ...

3
ответ дан 17 December 2019 в 07:05
поделиться

I'd create a class like this:


@MappedSuperclass
public abstract class AuditableDomainClass {
  private long createdBy;
  private long updatedBy;

  //getters and setters

Your entity classes that have the requirement you've described would simply extend this class, you'd set you variables in the layer you need to (controller for example) and you don't need to worry about it all the way down in the DAOs.

0
ответ дан 17 December 2019 в 07:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: