Hibernate вставка после сохранения - PullRequest
0 голосов
/ 31 октября 2019

В моем понимании у меня есть что-то вроде

public void insert(String type )
    Session s= dao.getCurrentSession();
    Long id=dao.getId();
    s.createQuery("insert into table1 t (id,msg,(select t2.typeId from table2 t2 where type =?)) VALUES (?,?,?)")
        .setParameter(0, id,       Hibernate.Long)
        .setParameter(1, "msg",    Hibernate.String)
        .setParameter(2, type,     Hibernate.String)
        .executeUpdate();
}

Я хочу изменить это на

public void insert(String type)
    Session s= dao.getCurrentSession();
    Long id=dao.getId();
    Long typeId=null;
    typeId=(Long)s.createQuery("select t2.type from table2 t2 where type =?").
            .setParameter(0, type,  Hibernate.String)
            .uniqueResult();

    if(typeId==null){
       Table2 t=new Table2(type);
       typeId=(Long)s.save(t);
    }
    s.createQuery("insert into table1 t (id,msg,Table2")) VALUES (?,?,?)
        .setParameter(0, id,      Hibernate.Long)
        .setParameter(1, "msg",   Hibernate.String)
        .setParameter(2, typeId,  Hibernate.Long)
        .executeUpdate();
}

После этой манипуляции я получаю исключение об ограничении, потому что у меня нет нового type с typeId в table2, однако в режиме отладки в IDEA я вижу, что typeId=s.save(t); возвращает новый id из вставки. Мой идентификатор генерируется с помощью Sequence in oracle.

Если я добавлю Transaction tx = s.beginTransaction() и tx.commit(), то получу новое исключение, что сессия закрыта и невозможно выполнить вставку.

Какчтобы избежать этого?

PS -----------------

Моя таблица2 равна

 public class Table2 implements Serializable {

  private static final long serialVersionUID = 6213740208940441112L;
  private Long typeId = null;
  private String type;

  public Table2 () {
  }

  public Table2 (String type) {
  this.type=type;
  }

  @Id
  @SequenceGenerator( name = "table_type", sequenceName = "seq_table_type", allocationSize = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "table_type")
  public Long getTypeId() {
    return this.typeId;
  }
  public void setId(Long id) {
    this.id = id;
  }

  @Column(name = "type", nullable = false)
  @NotNull
  public String getType() {
    return this.type;
  }

  public void setType(String type) {
    this.type= type;
  }

Ответы [ 2 ]

0 голосов
/ 31 октября 2019

Я нашел какое-то понимание

public void insert(String type)
    Session s= dao.getCurrentSession();
    Long id=dao.getId();
    Long typeId=(Long)s.createQuery("select typeId from table2 where type =?").
            .setParameter(0, type,  Hibernate.String)
            .uniqueResult();

    if(typeId==null){
       Table2 t=new Table2(type);
       typeId=(Long)s.save(t);
       s.flush();
    }
    s.createQuery("insert into table1 t (id,msg,Table2")) VALUES (?,?,?)
        .setParameter(0, id,      Hibernate.Long)
        .setParameter(1, "msg",   Hibernate.String)
        .setParameter(2, typeId,  Hibernate.Long)
        .executeUpdate();
        s.flush();
}

Но теперь я не могу откатить любые изменения, если получу какое-либо исключение, даже если я сделаю что-то подобное

 ...
} catch (Throwable e) {
        s.getTransaction().rollback();
}

Иэто происходит из-за последовательности Oracle не может сделать откат.

0 голосов
/ 31 октября 2019

Мне кажется, что вы меняете значение Long с именем typeId, но в вашей вставке вы по-прежнему используете входящий атрибут String с именем type.

Попробуйте изменить входящий тип или использовать созданный typeId в вашей вставке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...