---
title: "entityManager来主键查找类和entityManager.createQuery的区别"
author: "duyunfengsolo"
date: "2009-08-27T14:21:48Z"
tags: []
slug: "entitymanager-entitymanager-createquery"
draft: false
lastmod: "2009-08-27T14:21:48Z"
id: 458335
url: "https://solodu.iteye.com/blog/458335"
---

(1)首先看下代码：

```
public Long getServerIdBypublishWebsiteId(Long id) {
	Site tempSite = entityManager.find(Site.class, id);
//	Long serverId = (Long)entityManager.createQuery("SELECT s.serverId FROM Site s WHERE s.id= "+id).getSingleResult();
	if (tempSite != null && tempSite.getServerId() != null) {
		return tempSite.getServerId();
	} else {
		return null;
	}
}
```

 (2) Site tempSite = entityManager.find(Site.class, id);这种方式是通过主键来查找类的形式，一般情况下是这样用的。所以一般情况下如果知道主键的ID就应该先想到这种方式来查找类。

 (3) Long serverId = (Long)entityManager.createQuery("SELECT s.serverId FROM Site s WHERE s.id= "+id).getSingleResult();  
这种查询方式不适合用于主键的查询。至少我就在此碰到了错误：

```
错误场景的描述：
    我在site list的页面，当我点击delete的链接时，它删除成功了，但是页面却没有及时的更新即数据库中的这条记录已经删除了，而页面中这条记录还存在。所以当然啦这个主键的ID就依然存在。
    在删除这个数据之后它还会跳到本页面中，而这个时候(因为在本页面中它会去调用getServerIdBypublishWebsiteId这个方法)，如果用Long serverId = (Long)entityManager.createQuery("SELECT s.serverId FROM Site s WHERE s.id= "+id).getSingleResult();这种形式的话，页面就会报错。
    原因在什么地方呢？
    此时的id是有值的，但是不要忘记了数据库中是没有值的，恰在此时你要去调用getSingleResult，这个肯定会报错啦。原因就是这个。
    但是如果用Site tempSite = entityManager.find(Site.class, id);的话，就不会报错，虽然这个id是有值的，但是它从数据库里一查找这个Site的对象却没有发现，所以tempSite就是个空值，这样就不会报错的在页面中。
```

 

(4)所以以后如果有主键最好是想到那个find方法。