JPA设置了id,但实体不存在

时间:2017-06-26 11:50:06

标签: mysql spring-data eclipselink

我正在使用JPA(Eclipse-Link),Spring-Data和MySQL。我有事务(提交)和id生成的问题。我坚持一个实体(包含一个分离的实体),并在事务后我想使用id。生成了id,但实体管理器找不到此实体。

实施例: POJO:

private class Assignment {
private final Action action;

private Assignment(final Action action) {
    this.action = action;
}

public Action getAction() {
    return action;
}

}

JPA-实体

 @Entity
    public class Action {
        @ManyToOne(fetch = FetchType.LAZY, optional = false)
        private ActionType actionType;

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        Long id;
    }




@Entity
public class ActionType {
    String name;
}

服务:

    @Transactional(readOnly = true)
public class ActionManagement {

    EntityManager entityManager;

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Assignment assignAction(final ActionType type) {

        entityManager.detach(type);

        Action action = new Action();
        action.setActionType(type);

        action = entityManager.persist(action);
        // id is null, because here is commit or fluh triggerd.
        System.out.println(action.getId());

        return new Assignment(action);

    }
}

单元测试:

public void unitTest(){

    ActionType type = createRandomActionType();

    Assignment assignAction = actionManagement.assignAction(type);
    //ID is NOT null (e.d id:2), but the entity is null
    entityManager.find(Action.class,assignAction.getAction().getId())
}

当前的问题是,在事务之后,动作实体具有id,但在查找之后,实体始终为null。

有人知道出了什么问题吗?

提前致谢

0 个答案:

没有答案