EJB3.0 javax.persistence.PersistenceException: 错误。
我用MyEclipse 8.5 编写EJB项目,实现对单表操作。 数据源, 运行环境均没有问题。
运行时,报如下错误:
javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.d41741.entity.Testyry
这是session bean 接口代码:
package com.d41741.session;
import javax.ejb.Remote;
import com.d41741.entity.Testyry;
@Remote
public interface TyryRemote {
public int addUser(Testyry ty) ;
}
这是接口实现代码:
package com.d41741.session;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.d41741.entity.Testyry;
@Stateless
public class Tyry implements TyryRemote {
@PersistenceContext(unitName = "ejb_02PU")
protected EntityManager em ;
public int addUser(Testyry ty) {
// TODO Auto-generated method stub
em.persist(ty) ;
return ty.getPid();
}
}
这是client 访问代码:
package com.d41741.session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.d41741.entity.Testyry;
public class Ejb_client {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InitialContext ctx = new InitialContext() ;
TyryRemote te = (TyryRemote) ctx.lookup("Tyry/remote") ;
Testyry tr = new Testyry() ;
tr.setPname("ejb") ;
tr.setPsex(1) ;
te.addUser(tr);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是实体bean:
package com.d41741.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Testyry entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "testyry", catalog = "test")
public class Testyry implements java.io.Serializable {
// Fields
private Integer pid;
private String pname;
private Integer psex;
// Constructors
/** default constructor */
public Testyry() {
}
/** minimal constructor */
public Testyry(Integer pid) {
this.pid = pid;
}
/** full constructor */
public Testyry(Integer pid, String pname, Integer psex) {
this.pid = pid;
this.pname = pname;
this.psex = psex;
}
// Property accessors
@Id
@Column(name = "Pid", unique = true, nullable = false)
public Integer getPid() {
return this.pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
@Column(name = "Pname", length = 20)
public String getPname() {
return this.pname;
}
public void setPname(String pname) {
this.pname = pname;
}
@Column(name = "Psex")
public Integer getPsex() {
return this.psex;
}
public void setPsex(Integer psex) {
this.psex = psex;
}
}
感谢各位来看本帖子的大虾们! 谢谢各位啦。
[解决办法]
@Id
@Column(name = "Pid", unique = true, nullable = false)
问题就出在这里,你表的主键是不允许空的,但是你的客户端
Testyry tr = new Testyry() ;
tr.setPname("ejb") ;
tr.setPsex(1) ;
te.addUser(tr);
根本就没有给id赋值,但是你又没有指定该主键是自动生成的,所以往数据库中插入的时候就没有主键,所以无法插入了