使用Spring Hibernate Sessionfactory从数据库中选择单个项目

时间:2011-09-16 15:07:44

标签: java hibernate spring sessionfactory

这是在我的DAO中:

public List<Weather> getCurrentWeather() {  
    return sessionFactory.getCurrentSession().createQuery("from Weather").list();
}

这可以从表天气中获取所有元素。但是,我想说我想做这样的事情(我只希望表天气中有一个元素):

public Weather getCurrentWeather() {    
    return sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
}

我知道最后不应该有 list() ,但我必须在那里写什么才能获得一个对象?

3 个答案:

答案 0 :(得分:11)

如果你有一个id,你只需使用get:

public Weather getCurrentWeather() {    
    return sessionFactory.getCurrentSession().get(Weather.class, 1); 
}

如果您确实需要进行查询,是的,您必须抓住结果集的顶部,或者您可以在查询中使用uniqueResult()

答案 1 :(得分:9)

获取列表有什么问题吗? :)即使你知道只有1个休眠也不能假设。无论如何,获取清单更安全!

public Weather getCurrentWeather() {    
    List<Weather> list = sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
    return (list.isEmpty() ? null : list.get(0));
}

答案 2 :(得分:0)

您需要使用Criteria API,如下所示:

import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';

@Component({
    selector: 'app',
    template: `
      <b>Angular 2 Component Using Observables!</b>

      <h6 style="margin-bottom: 0">VALUES:</h6>
      <div *ngFor="let value of values">- {{ value }}</div>

      <h6 style="margin-bottom: 0">ERRORs:</h6>
      <div>Errors: {{anyErrors}}</div>

      <h6 style="margin-bottom: 0">FINISHED:</h6>
      <div>Finished: {{ finished }}</div>

      <button style="margin-top: 2rem;" (click)="init()">Init</button>
    `
})
export class MyApp {

  private data: Observable<Array<number>>;
  private values: Array<number> = [];
  private anyErrors: boolean;
  private finished: boolean;

  constructor() {
  }

  init() {
      this.data = new Observable(observer => {
          setTimeout(() => {
              observer.next(42);
          }, 1000);

          setTimeout(() => {
              observer.next(43);
          }, 2000);

          setTimeout(() => {
              observer.complete();
          }, 3000);
      });

      let subscription = this.data.subscribe(
          value => this.values.push(value),
          error => this.anyErrors = true,
          () => this.finished = true
      );
  }

}