使用一对多的收益休眠

时间:2018-07-01 13:43:22

标签: java hibernate

我是新来的冬眠者,很抱歉,如果问题可能很愚蠢,但我尝试搜索答案却找不到解决方法。

我有2个表“ question”和“ possibleAnswers”, 关系是oneToMany(意味着每个问题几乎没有答案) DB在2个表之间有FK并且我运行hibernate配置来自动创建hibernate文件,当我获取数据时,如果我有3个问题和4个答案(1个Q有2个可能的答案),我将得到交叉联接的意思。获得4条记录的过程我获得12条记录 我不知道我的地图是错误的还是正在使用的HQL。

所有相关文件

这是我在日志中看到的

package stackOv;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Threads {

  public static void main(String[] args) {
    Threads o = new Threads();
    System.out.println("main thread is: " + Thread.currentThread().getName());
    o.mainThreadRun();
  }

  // the timer will push tasks to the queue
  // the main thread will execute tasks from this queue
  // (the main thread should be the only worker!)
  BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();

  // the main thread executes this
  void mainThreadRun() {
    // the main thread starts the timer
    threadB();

    while (!Thread.interrupted()) {
      try {
        // waits for a task to become available
        // if the queue is empty, waits until a task is submitted
        Runnable task = tasks.take();
        // execute the task
        task.run();
      } catch (InterruptedException e) {
        System.out.println("interrupted");
        return;
      }
    }
  }

  // executed in the main thread; spawns a timer
  void threadB() {
    Timer t = new Timer();
    TimerTask tt = new TimerTask() {
      @Override
      public void run() {
        try {
          tasks.put(new Runnable() {
            @Override
            public void run() {
              doSomeStuff();
            }
          });
        } catch (InterruptedException e) {
          System.out.println("error");
        }
      }
    };
    t.schedule(tt, 1000, 1000);
  }

  void doSomeStuff() {
    System.out.println("doSomeStuff: executing from thread=" + Thread.currentThread().getName());
  }
}

这是我正在运行的Java代码 getQuestions.java:

select
    questions0_.question_id as question1_4_0_,
    possiblean1_.possible_answer_id as possible1_3_1_,
    questions0_.answer_type as answer_t2_4_0_,
    questions0_.display_order as display_3_4_0_,
    questions0_.question_text as question4_4_0_,
    possiblean1_.answer_value as answer_v2_3_1_,
    possiblean1_.question_id as question3_3_1_ 
from
    edi_ms.questions questions0_ cross 
join
    edi_ms.possible_answers possiblean1_

Questions.java

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session =   sessionFactory.openSession();
Query<Questions> query = session.createQuery("from Questions, PossibleAnswers");
List<Questions> questions = (List<Questions>)query.list();
return questions

Questions.hbm.xml

@Entity
@Table(name = "questions", schema = "edi_ms")
public class Questions implements java.io.Serializable {

private long questionId;

private String questionText;
private String answerType;
private Long displayOrder;
private Set<PossibleAnswers> possibleAnswerses = new HashSet<PossibleAnswers>(0);
public Questions() {
}

public Questions(long questionId, 
                String questionText) {
    this.questionId = questionId;
    this.questionText = questionText;
}

public Questions(long questionId, 
        String questionText, String answerType, Long displayOrder,
        Set<PossibleAnswers> possibleAnswerses, Set<MembersAnswers> membersAnswerses) {
    this.questionId = questionId;
    this.questionText = questionText;
    this.answerType = answerType;
    this.displayOrder = displayOrder;
    this.possibleAnswerses = possibleAnswerses;
}

@Id

@Column(name = "question_id", unique = true, nullable = false)
public long getQuestionId() {
    return this.questionId;
}

public void setQuestionId(long questionId) {
    this.questionId = questionId;
}

@Column(name = "question_text", nullable = false)
public String getQuestionText() {
    return this.questionText;
}

public void setQuestionText(String questionText) {
    this.questionText = questionText;
}

@Column(name = "answer_type", length = 1)
public String getAnswerType() {
    return this.answerType;
}

public void setAnswerType(String answerType) {
    this.answerType = answerType;
}

@Column(name = "display_order")
public Long getDisplayOrder() {
    return this.displayOrder;
}

public void setDisplayOrder(Long displayOrder) {
    this.displayOrder = displayOrder;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "questions")
@JsonbTransient
public Set<PossibleAnswers> getPossibleAnswerses() {
    return this.possibleAnswerses;
}

@JsonbTransient
public void setPossibleAnswerses(Set<PossibleAnswers> possibleAnswerses) {
    this.possibleAnswerses = possibleAnswerses;
}
}

PossibleAnswers.java

<hibernate-mapping auto-import="true" default-access="property" default- 
cascade="none" default-lazy="true">
<class dynamic-insert="false" dynamic-update="false" mutable="true" name="HibernateDBFiles.Questions" optimistic-lock="version" polymorphism="implicit" schema="edi_ms" select-before-update="false" table="questions">
    <id name="questionId" type="long">
        <column name="question_id"/>
        <generator class="assigned"/>
    </id>

    <property generated="never" lazy="false" name="questionText" optimistic-lock="true" type="string" unique="false">
        <column name="question_text" not-null="true"/>
    </property>
    <property generated="never" lazy="false" name="answerType" optimistic-lock="true" type="string" unique="false">
        <column length="1" name="answer_type"/>
    </property>
    <property generated="never" lazy="false" name="displayOrder" optimistic-lock="true" type="java.lang.Long" unique="false">
        <column name="display_order"/>
    </property>
    <set embed-xml="true" fetch="select" inverse="true" lazy="true" mutable="true" name="possibleAnswerses" optimistic-lock="true" sort="unsorted" table="possible_answers">
        <key on-delete="noaction">
            <column name="question_id" not-null="true"/>
        </key>
        <one-to-many class="HibernateDBFiles.PossibleAnswers" embed-xml="true" not-found="exception"/>
    </set> 

</class>

PossbleAnswers.hbm.xml

@Entity
@Table(name = "possible_answers", schema = "edi_ms")
public class PossibleAnswers implements java.io.Serializable {

private long possibleAnswerId;
private Questions questions;
private String answerValue;


public PossibleAnswers() {
}

public PossibleAnswers(long possibleAnswerId, Questions questions, String answerValue) {
    this.possibleAnswerId = possibleAnswerId;
    this.questions = questions;
    this.answerValue = answerValue;
}



@Id

@Column(name = "possible_answer_id", unique = true, nullable = false)
public long getPossibleAnswerId() {
    return this.possibleAnswerId;
}

public void setPossibleAnswerId(long possibleAnswerId) {
    this.possibleAnswerId = possibleAnswerId;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id", nullable = false)
@JsonbTransient
public Questions getQuestions() {
    return this.questions;
}
@JsonbTransient
public void setQuestions(Questions questions) {
    this.questions = questions;
}

@Column(name = "answer_value", nullable = false, length = 50)
public String getAnswerValue() {
    return this.answerValue;
}

public void setAnswerValue(String answerValue) {
    this.answerValue = answerValue;
}


}

2 个答案:

答案 0 :(得分:0)

这里的查询是错误的,更新的查询是

   SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session =   sessionFactory.openSession();
Query<Questions> query = session.createQuery("from Questions");
List<Questions> questions = (List<Questions>)query.list();
return questions

答案 1 :(得分:0)

谢谢大家的帮助。 我发现了问题,原来的查询现在可以正常工作了,不需要遍历响应

Query<Questions> query = session.createQuery("from Questions ");

问题在于,由于我使用的是JSON,因此我添加了

@JsonbTransient

中的

在MayaAnswers.java中

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id", nullable = false)
@JsonbTransient
public Questions getQuestions() {
    return this.questions;
}
@JsonbTransient
public void setQuestions(Questions questions) {
    this.questions = questions;
}

据我了解,这样做是为了防止无限循环(在我添加它之前,这是发生了的事情) 问题是我也将此添加到Questions.java 一旦我删除它,它的工作原理! (如果有人想了解有关@JsonbTransient的更多信息)