enitityManager.find和entityManager.createQuery有什么区别?

时间:2010-12-02 20:26:46

标签: java hibernate tomcat persistence ejb-3.0

好的,我正在使用带有hibernate的EJB 3.0,我们将.ear文件放入嵌入Apache Tomcat 6.0.18的Easy-Beans 1.0.1(带有Hibernate)部署目录中。 所以我的数据库必须坚持这样的事情:

@Entity
@Table(name="AUTHOR")
public class Author implements Serializable {

//////////////////////////////////////////////////////////////////
// Fields
//////////////////////////////////////////////////////////////////

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "A_ID", unique=true, nullable = false)
private Integer id;

@Column (name = "A_NAME", unique = false, nullable = false)
private String name;

@Column (name = "A_LASTNAME", unique = false, nullable = false)
private String lastname;

@OneToMany(cascade = {ALL}, fetch = EAGER, mappedBy = "author")
private Set<BookAuthor> bookAuthors = new HashSet<BookAuthor>();

  @Override
  public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      Author author = (Author) o;

      if (id != null ? !id.equals(author.id) : author.id != null) return false;

      return true;
  }

  @Override
  public int hashCode() {
      return id != null ? id.hashCode() : 0;
  }  
}

@Entity
@Table(name = "BOOK" )
public class Book implements Serializable {
//////////////////////////////////////////////////////////////////
// Fields
//////////////////////////////////////////////////////////////////
@Id
@GeneratedValue (strategy = IDENTITY)
@Column(name = "B_ID", unique = true, nullable = false)
private Integer bid;

@Column(name = "B_YEAR", unique = false, nullable = true)
private Integer year;

@Column(name = "B_ISBN", unique = false, nullable = false)
private String isbn;

@Column(name = "B_TITLE", unique = false, nullable = false)
private String title;

@OneToMany(cascade = {ALL}, fetch = EAGER, mappedBy = "book")
private Set<BookAuthor> bookAuthors = new HashSet<BookAuthor>();

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Book book = (Book) o;

    if (isbn != null ? !isbn.equals(book.isbn) : book.isbn != null) return false;
    if (bid != null ? !kid.equals(book.bid) : book.bid != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = bid != null ? bid.hashCode() : 0;
    result = 31 * result + (isbn != null ? isbn.hashCode() : 0);
    return result;
  }

}

@Entity
@Table(name = "BOOK_AUTHOR")
public class BookAuthor implements Serializable {

  //////////////////////////////////////////////////////////////////
  // Fields
  //////////////////////////////////////////////////////////////////
  @Id
  @GeneratedValue(strategy = IDENTITY)
  @Column(name = "BA_ID", unique=true, nullable = false)
  private Integer id;

  @Column(name = "BA_ROLE", unique = false, nullable = true)
  private String role;

  @ManyToOne
  @JoinColumn (name = "A_ID", referencedColumnName = "A_ID", nullable = false)
  private Author author;

  @ManyToOne
  @JoinColumn (name = "B_ID", referencedColumnName = "B_ID", nullable = false)
  private Book book;

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    BookAuthor that = (BookAuthor) o;

    if (auhtor != null ? !author.equals(that.author) : that.author != null) return false;
    if (book != null ? !book.equals(that.book) : that.book!= null) return false;
    if (id != null ? !id.equals(that.id) : that.id != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = id != null ? id.hashCode() : 0;
    result = 31 * result + (author != null ? author.hashCode() : 0);
    result = 31 * result + (book != null ? book.hashCode() : 0);
    return result;
  }

}

因此,当删除项目时,我有一个类似这样的实体bean:

@Stateless
@Local(DeleteBookAuthor.class)
public class DeleteBookAuthorBean implements DeleteBookAuthor
{

   @PersistenceContext(unitName="Library")
   protected EntityManager em;

   @Override
   public void removeById(Integer id) {
      try{

        Query q = em.createQuery("SELECT ba FROM BookAuthor ba WHERE id = ?1");
        q.setParameter(1,id);

        BookAuthor ba = (BookAuthor) q.getSingleResult();

        ba.getAuthor().getBookAuthors().remove(ba);
        ba.getBook().getBookAuthors().remove(ba);

        em.remove(ba);
      }catch (Exception e){
         e.printStackTrace();
      }
   }
}

不幸的是,当我的Servlet调用这个bean时,它返回一个“已传递给持久化的已删除实体”异常;然而改变线:

Query q = em.createQuery("SELECT ba FROM BookAuthor ba WHERE id = ?1");
q.setParameter(1,id);        
BookAuthor ba = (BookAuthor) q.getSingleResult(); 

BookAuthor ba = em.find(BookAuthor.class, id)

让问题消失。我问的问题是为什么?在类似的情况下,我使用em.createQuery来检索和删除多个实体,并且它顺利运行。那为什么它现在不起作用呢?

更新:致电 Query q=...然后删除BookAuthors会从BookAuthors中删除Books,但不会从Authors中删除ba。在第二种情况下,它从两组中删除。 true使用baQuery.equals(baFind)时,remove具有相同的哈希值并返回query

根据是否调用find / {{1}}来解释为什么两个函数返回同一个对象但调用{{1}}的行为会有所不同?

2 个答案:

答案 0 :(得分:3)

也许这与equals()中缺少hashCode() / BookAuthor有关。如果是这样,在查询的情况下,您有几个具有相同状态的BookAuthor不同实例,因此不会从AuthorBook中的相应集中删除它们。 / p>

答案 1 :(得分:1)

据我所知,Query.getSingleResult()在某些情况下会刷新会话,我不确定EntityManager.find()。我会遵循axtavt的建议并仔细检查你的实体是否正确地从集合中删除。我还会在em.remove(ba);之前调用此声明,以确保您的ba对象重新附加到会话中:

ba = em.merge(ba);