hql, hibernate - вставить в связанную таблицу - PullRequest
0 голосов
/ 29 декабря 2011

У меня есть небольшая проблема.

У меня есть две таблицы Pool и PoolQuestion:

Pool:

    package com.pool.app.domain;

// Generated 2011-12-28 23:05:46 by Hibernate Tools 3.4.0.CR1

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Pool generated by hbm2java
 */
@Entity
@Table(name = "pool", catalog = "pool")
public class Pool implements java.io.Serializable {

    private Integer id;
    private String name;
    private String slug;
    private Date dateCreate;
    private Date deactivationDate;
    private int creatorId;
    private int active;
    private Set<PoolQuestion> poolQuestions = new HashSet<PoolQuestion>(0);

    public Pool() {
    }

    public Pool(String name, String slug, int creatorId, int active) {
        this.name = name;
        this.slug = slug;
        this.creatorId = creatorId;
        this.active = active;
    }

    public Pool(String name, String slug, Date dateCreate,
            Date deactivationDate, int creatorId, int active,
            Set<PoolQuestion> poolQuestions) {
        this.name = name;
        this.slug = slug;
        this.dateCreate = dateCreate;
        this.deactivationDate = deactivationDate;
        this.creatorId = creatorId;
        this.active = active;
        this.poolQuestions = poolQuestions;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "name", nullable = false, length = 200)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "slug", nullable = false, length = 200)
    public String getSlug() {
        return this.slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "date_create", length = 19)
    public Date getDateCreate() {
        return this.dateCreate;
    }

    public void setDateCreate(Date dateCreate) {
        this.dateCreate = dateCreate;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "deactivation_date", length = 19)
    public Date getDeactivationDate() {
        return this.deactivationDate;
    }

    public void setDeactivationDate(Date deactivationDate) {
        this.deactivationDate = deactivationDate;
    }

    @Column(name = "creator_id", nullable = false)
    public int getCreatorId() {
        return this.creatorId;
    }

    public void setCreatorId(int creatorId) {
        this.creatorId = creatorId;
    }

    @Column(name = "active", nullable = false)
    public int getActive() {
        return this.active;
    }

    public void setActive(int active) {
        this.active = active;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pool")
    public Set<PoolQuestion> getPoolQuestions() {
        return this.poolQuestions;
    }

    public void setPoolQuestions(Set<PoolQuestion> poolQuestions) {
        this.poolQuestions = poolQuestions;
    }

}

и PoolQuestion:

 package com.pool.app.domain;

// Generated 2011-12-28 23:05:46 by Hibernate Tools 3.4.0.CR1

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * PoolQuestion generated by hbm2java
 */
@Entity
@Table(name = "pool_question", catalog = "pool")
public class PoolQuestion implements java.io.Serializable {

    private Integer id;
    private Pool pool;
    private String answer;
    private int order;
    private String question;
    private int value;

    public PoolQuestion() {
    }

    public PoolQuestion(Pool pool, String answer, int order, int value) {
        this.pool = pool;
        this.answer = answer;
        this.order = order;
        this.value = value;
    }

    public PoolQuestion(Pool pool, String answer, int order, String question,
            int value) {
        this.pool = pool;
        this.answer = answer;
        this.order = order;
        this.question = question;
        this.value = value;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "poolid", nullable = false)
    public Pool getPool() {
        return this.pool;
    }

    public void setPool(Pool pool) {
        this.pool = pool;
    }

    @Column(name = "answer", nullable = false, length = 500)
    public String getAnswer() {
        return this.answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    @Column(name = "order", nullable = false)
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    @Column(name = "question", length = 500)
    public String getQuestion() {
        return this.question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    @Column(name = "value", nullable = false)
    public int getValue() {
        return this.value;
    }

    public void setValue(int value) {
        this.value = value;
    }

}

Я хочу вставить значения в PoolQuery, но есть поле (poolid), которое связано с таблицей пула.

В POJO поле (poolid) было отображено как «Пул».

Как я могу вставить значение в PoolQuestion, потому что такой код:

PoolQuestion poolQuestion = new PoolQuestion();

    Transaction transaction = session.beginTransaction();

    poolQuestion.setAnswer(answer);
    poolQuestion.setPool(1);
    poolQuestion.setValue(0);

    session.save(poolQuestion);

    transaction.commit();

не работает.

Пожалуйста, помогите!

Ответы [ 2 ]

2 голосов
/ 29 декабря 2011

Вы хотите связать вопрос с существующим пулом.Этот пул имеет идентификатор 1 и находится в базе данных.Таким образом, вы не хотите создавать новый пул.new Pool(), таким образом, не то, что вы хотите.Пул находится в базе данных.Для получения сущностей из базы данных необходимо использовать сеанс Hibernate.Поэтому вы просите сеанс Hibernate получить пул с идентификатором 1 из базы данных:

Pool pool = session.get(Pool.class, 1);

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

question.setPool(pool);
pool.getQuestions.add(question);

И, наконец, вы хотите, чтобы вопрос сохранялся в базе данных:

session.persist(question); // or save

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

0 голосов
/ 29 декабря 2011

Прежде всего, не передавайте int, а Pool экземпляр PoolQuestion.setPool(). А затем либо сохраните экземпляр Pool перед сохранением PoolQuestion, либо используйте каскадное сохранение :

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.SAVE_UPDATE)
@JoinColumn(name = "poolid", nullable = false)
public Pool getPool() {
  return this.pool;
}

Надеюсь, это поможет.

...