Объединить и получить версию, подлежащую обновлению, без сброса?

Можно ли изменить экземпляр объекта с версией и получить версию, которая должна быть увеличена без использования очистки? Потому что из того, что я читал, Боюсь, что промывка - не лучшая практика, потому что это плохо сказывается на производительности или даже повреждении данных? Я не уверен: D


Вот простой код, а также вывод в виде комментария:

/*
    Hibernate: select receivingg0_.id as id9_14_, receivingg0_.creationDate as creation2_9_14_, ... too long
    the version before modification : 16
    the version after modification : 16
    after merge the modification, the version is : 16
    Hibernate: update ReceivingGood set creationDate=?, modificationDate=?, usercreate_id=?, usermodify_id=?,  ... too long
    after flushing the modification, the version is finally : 17
*/
public void modifyHeaderAndGetUpdatedVersion() {
    String id = "3b373f6a-9cd1-4c9c-9d46-240de37f6b0f";
    ReceivingGood receivingGood = em.find(ReceivingGood.class, id);
    System.out.println("the version before modification : " + receivingGood.getVersion());

    receivingGood.setTransactionNumber("NUM001xyz");
    System.out.println("the version after modification : " + receivingGood.getVersion());

    receivingGood = em.merge(receivingGood);
    System.out.println("after merge the modification, the version is : " + receivingGood.getVersion());

    em.flush();
    System.out.println("after flushing the modification, the version is finally : " + receivingGood.getVersion());
}

В моем тесте версия увеличивалась после сброса. Экземпляр, возвращенный из операции слияния, не имеет увеличенной версии.

Но в моем случае я хотел бы вернуть объект в свой webui в форме DTO, и объект должен иметь версию после сброса / фиксации прежде чем преобразовать его в DTO и вернуть в пользовательский интерфейс для визуализации. И тогда пользовательский интерфейс может иметь последнюю версию и будет передавать эту версию для следующей отправки.


Есть ли способ получить последнюю версию, не выполняя сброса?

Спасибо!


ОБНОВЛЕНИЕ


]По моему опыту, увеличивать это вручную может быть проблематично, как видно из этого примера ниже. В этом примере у нас 2 сброса.

Первый - синхронизировать изменения в соединении с базой данных, чтобы вызов хранимой процедуры из того же соединения мог видеть изменения, сделанные из entityManager.

Второй флеш вызывается для получения окончательной версии. И мы видим, что это увеличивается вдвое . Таким образом, получение версии только из ручного приращения без промывки не будет работать в этом состоянии, так как мы должны действительно подсчитать, сколько выполняется сбросов.

/*
Hibernate: select receivingg0_.id as id9_14_, receivingg0_.creationDate as creation2_9_14_, .. too long
the version before modification : 18
the version after modification : 18
after merge the modification, the version is : 18
now flushing the modification, so that the stored procedure call from the same connection can see the changes
Hibernate: update ReceivingGood set creationDate=?, modificationDate=?, usercreate_id=?, .. too long
after flushing the modification, the version is : 19
Hibernate: update ReceivingGood set creationDate=?, modificationDate=?, usercreate_id=?, .. too long
after the second flush, the version got increased again into : 20
*/
public void modifyHeaderAndGetUpdatedVersionWith2Flushes() {
    String id = "3b373f6a-9cd1-4c9c-9d46-240de37f6b0f";
    ReceivingGood receivingGood = em.find(ReceivingGood.class, id);
    System.out.println("the version before modification : " + receivingGood.getVersion());

    //auditEntity(receivingGood, getUser("3978fee3-9690-4377-84bd-9fb05928a6fc"));
    receivingGood.setTransactionNumber("NUM001xyz");
    System.out.println("the version after modification : " + receivingGood.getVersion());

    receivingGood = em.merge(receivingGood);
    System.out.println("after merge the modification, the version is : " + receivingGood.getVersion());
    System.out.println("now flushing the modification, so that the stored procedure call from the same connection can see the changes");
    em.flush();
    System.out.println("after flushing the modification, the version is : " + receivingGood.getVersion());

    receivingGood.setTransactionNumber("NUM001abc");

    em.flush();
    System.out.println("after the second flush, the version got increased again into : " + receivingGood.getVersion());
}

Означает ли это, что мне действительно нужно полагаться на флеш в конце, чтобы получить последнюю версия для измененного объекта?


ОБНОВЛЕНИЕ 2


Здесь ' { public Guid Id {get; set;} публичная строка Имя {get; set;}} создать таблицу Foo ( id uniqueidentifier первичный КЛЮЧ ПО УМОЛЧАНИЮ (newsequentialid ()), name ...

У меня есть этот класс и таблица:

public class Foo
{
public Guid Id {get;set;}
public string Name {get;set;}   
}

create table Foo
(
id uniqueidentifier primary KEY DEFAULT (newsequentialid()),
name nvarchar(255)
)

проблема в том, что когда я пытаюсь сохранить новый foo, первый идет с 0000-000-00 ... id, а второй тоже, поэтому я получить исключение ограничения

кто-нибудь знает исправление?

39
задан ahmadali shafiee 10 June 2012 в 20:19
поделиться