EclipseLink的@UuidGenerator导致NullPointerException

时间:2014-12-07 22:48:19

标签: java java-ee eclipselink uuid

我试图开始使用EclipseLink的@UuidGenerator annonation进行ID生成,但NPE失败了。

我正在使用Java EE 6 + GlassFish 4.1。实体是从servlet创建的。 EclipseLink版本是2.6.0-M3。简单的长ID“@GeneratedValue(strategy = GenerationType.AUTO)”工作正常。

实体代码:

@Entity
@UuidGenerator(name="QUANTITY_GEN")
public class Quantity implements Serializable 
{
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(generator = "QUANTITY_GEN")
    private String id;

...

}

Servlet代码:

@WebServlet(name = "Qtest", urlPatterns =
{
    "/Qtest"
})
public class Qtest extends HttpServlet
{
    @EJB
    private QuantityFacade quantityFacade;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        ...

        Quantity qt = new Quantity();
        quantityFacade.create(qt);

        ...
    }
}

跟踪:

Caused by: java.lang.NullPointerException
    at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1067)
    at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:361)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:320)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:486)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4290)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4235)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
    at uuidtest.AbstractFacade.create(AbstractFacade.java:24)

请告知可能有一些明显的错误?

2 个答案:

答案 0 :(得分:3)

看起来它确实是EclipseLink的错误,很快就会修复,所以我使用了一种解决方法 - 如此处所述的直接id生成http://blog.xebia.com/2009/06/03/jpa-implementation-patterns-using-uuids-as-primary-keys/

@Id
private String id;

public AbstractBaseEntity() {
    this.id = UUID.randomUUID().toString();
}

答案 1 :(得分:1)

我使用以下代码来解决问题。在使用BeanUtils.copyProperties()时,使用默认构造函数在使用复合键克隆实体方面遇到了问题。因此我使用了@PrePersist。这是在第一次在数据库中创建行之前调用的

@MappedSuperclass
@Getter
@Setter
public abstract class AbstractMasterUUIDEntity extends AbstractMasterEntity<String> {

    @Id
    private String id;

    @PrePersist
    public void generateId() {
        if(this.id == null ) {
            this.id = UUID.randomUUID().toString();
        }
    }

}