我为学习目的制作了一个简单的CRUD应用程序,它使用webservices(带有jersey),EJB和JPA(eclipse link + mysql)。我起初显然已经创建了一个名为User
的实体类,并尝试返回它,例如通过ID(带有namedquery)搜索它之后:
public User findById(Integer id) {
return em.createNamedQuery("User.findById", User.class).setParameter("id", id).getSingleResult();
}
并且它工作正常(只是查找位),但在返回时使用:
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_XML)
public User find(@PathParam("id") String id) {
return db.find(id);
}
(在dao和上面这个之间有另一层)它总是产生一个内部服务器错误,在glassfish控制台中没有任何错误。
Response:
status: 500 Internal Server Error
Date: Mon, 02 Mar 2015 07:02:08 GMT
Server: GlassFish Server Open Source Edition 4.1
Connection: close
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.7)
Content-Length: 1154
The server encountered an internal error that prevented it from fulfilling this request.
我的实体类如下:
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name="Users")
@NamedQueries({ @NamedQuery(name="User.getAll",
query="SELECT u FROM User u"),
@NamedQuery(name="User.findByName",
query="SELECT u FROM User u WHERE u.name = :name"),
@NamedQuery(name="User.getCount",
query="SELECT COUNT(u) FROM User u"),
@NamedQuery(name="User.findById",
query="SELECT u FROM User u WHERE u.id = :id"),
})
@XMLRootElement
public class User implements Serializable{
@Id
@Column(name="Id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="Name")
private String name;
private static final long serialVersionUID = 1L;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
现在我尝试从User中提取界面,并将其称为user,将实体重命名为UserEntity并创建一个实现User界面的新类 - UserXML。它是基本的,只是带有getter,setter和XML注释的id / name字段。当我返回用户时,我现在做这样的事情:
public User findById(Integer id) {
UserEntity user = em.createNamedQuery("User.findById", UserEntity.class).setParameter("id", id).getSingleResult();
System.out.println("returning " + user.toString());
User userxml = new UserXML();
userxml.setId(user.getId());
userxml.setName(user.getName());
return userxml;
}
它完美无缺。为什么?在我的第一种方法中,我做错了什么?