我创建了一个bean:
package beans;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import mazeJPA.Forumcategory;
/**
* Session Bean implementation class ForumBean
*/
@Stateless
@LocalBean
public class ForumBean
{
@PersistenceContext(unitName = "mazeEJB")
private EntityManager em;
/**
* Default constructor.
*/
public ForumBean(){}
public List<Forumcategory> getCategories()
{
return em.createNamedQuery
(
"Forumcategory.findAll", Forumcategory.class
).getResultList();
}
}
及其实体类
package mazeJPA;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the forumcategory database table.
*
*/
@Entity
@Table(name="forumcategory")
@NamedQuery(name="Forumcategory.findAll", query="SELECT f FROM Forumcategory f")
public class Forumcategory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int cid;
private String desc;
private String name;
public Forumcategory() {
}
public int getCid() {
return this.cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getDesc() {
return this.desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
当我从servlet调用getCategories()时,我得到一个sql异常:
Internal Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'DESC, NAME FROM
forumcategory' at line 1 Error Code: 1064 Call: SELECT CID, DESC, NAME
FROM forumcategory Query: ReadAllQuery(name="Forumcategory.findAll"
referenceClass=Forumcategory sql="SELECT CID, DESC, NAME FROM
forumcategory")
我的表是:
cid INT NOT NULL, name VARCHAR(255) NOT NULL, desc TEXT NOT NULL,
PRIMARY KEY (cid)
我不知道为什么会这样。我的映射有问题吗?我最近才在我的项目中添加了这个与它有关的事项,即我是否必须立即生成所有表格?
答案 0 :(得分:2)
DESC
是一个 reserved sql word ,所以你必须使用desc
来代替它,例如
SELECT CID, `DESC`, NAME FROM ...
答案 1 :(得分:1)
DESC是大多数SQL中的保留关键字。似乎您的JPA提供程序不会为您自动转义这些(引号括起来)。一些JPA实现(例如DataNucleus JPA)为您做到了这一点。