1

当我使用 JPA 时,我的 oracle 数据库表有一个基本问题。

我的问题是,我通过在数据库中添加一个 ID 列来创建表。当我回到我的 JPA 项目时,当我尝试创建新条目时,它不会为新条目创建 ID。它总是说:尝试回滚事务时发生错误。

我搜索一下这个问题。它基本上不会自动生成 ID 值。这是我的 JPA 控制器类:

@Entity
@Table(name = "PROJECTS", catalog = "", schema = "PROJETAKIP")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Projects.findAll", query = "SELECT p FROM Projects p"),
    @NamedQuery(name = "Projects.findById", query = "SELECT p FROM Projects p WHERE p.id = :id"),
    @NamedQuery(name = "Projects.findByProject", query = "SELECT p FROM Projects p WHERE p.project = :project")})
public class Projects implements Serializable {
    private static final long serialVersionUID = 1L;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Id
    @Basic(optional = false)
    @Column(name = "ID", nullable = false, precision = 0, scale = -127)
    @GeneratedValue(strategy= GenerationType.SEQUENCE)
    private BigDecimal id;
    @Column(name = "PROJECT", length = 255)
    private String project;

    public Projects() {
    }

    public Projects(BigDecimal id) {
        this.id = id;
    }

    public BigDecimal getId() {
        return id;
    }

    public void setId(BigDecimal id) {
        this.id = id;
    }

    public String getProject() {
        return project;
    }

    public void setProject(String project) {
        this.project = project;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Projects)) {
            return false;
        }
        Projects other = (Projects) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.ibb.souce.Projects[ id=" + id + " ]";
    }

}

这是我的 JSFClass:

@ManagedBean(name = "projectsController")
@SessionScoped
public class ProjectsController implements Serializable {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "DenemelerPU")
    private EntityManagerFactory emf = null;
    private Projects current;
    private DataModel items = null;
    private ProjectsJpaController jpaController = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public ProjectsController() {
    }

    public Projects getSelected() {
        if (current == null) {
            current = new Projects();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ProjectsJpaController getJpaController() {
        if (jpaController == null) {
            jpaController = new ProjectsJpaController(utx, emf);
        }
        return jpaController;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getJpaController().getProjectsCount();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getJpaController().findProjectsEntities(getPageSize(), getPageFirstItem()));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Projects) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Projects();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getJpaController().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Projects) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getJpaController().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Projects) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getJpaController().destroy(current.getId());
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getJpaController().getProjectsCount();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getJpaController().findProjectsEntities(1, selectedItemIndex).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(getJpaController().findProjectsEntities(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(getJpaController().findProjectsEntities(), true);
    }

    @FacesConverter(forClass = Projects.class)
    public static class ProjectsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ProjectsController controller = (ProjectsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "projectsController");
            return controller.getJpaController().findProjects(getKey(value));
        }

        java.math.BigDecimal getKey(String value) {
            java.math.BigDecimal key;
            key = new java.math.BigDecimal(value);
            return key;
        }

        String getStringKey(java.math.BigDecimal value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Projects) {
                Projects o = (Projects) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Projects.class.getName());
            }
        }
    }
}

当我手动分配 ID 时,它可以完美运行。但我想要的是,它必须自动生成价值。如何克服这一点?

我的触发器:DELIMITER @@ CREATE OR REPLACE TRIGGER PROJETAKIP.PROJECTS_TRIGGER BEFORE INSERT ON PROJECTS REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT PROJECTS_SEQUENCE.nextval INTO :NEW.ID FROM dual;END; @@ DELIMITER ;

4

2 回答 2

0

序列策略

这就是你应该如何使用序列生成器:

@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="seq")

在课堂上:(例如,在 之后@Entity

@SequenceGenerator(name="seq", sequenceName="PROJECTS_SEQUENCE", initialValue=1)

这应该适合你。

于 2013-03-03T18:29:13.407 回答
0

在保存对象时,我遇到了同样的错误。我的原因是因为将 3 位数的 MIN 范围添加到 id 值。默认情况下,自动生成的 id 将从 1、2、3 开始......我做了:

@Id @GeneratedValue
    @Basic(optional = false)
    @Size(min = 1, max = 64, message = "ID must be between 1 and 64 characters")
    private String id;

所以 - 在你的情况下 - 小心你的 id 注释 - 尝试在没有比例、最小值和最大值的情况下启动 - 查看结果。例如,尝试:

    @Id
    @Basic(optional = false)
    @Column(name = "ID")
    @GeneratedValue(strategy= GenerationType.AUTO)
    private BigDecimal id;
于 2017-03-20T18:42:57.990 回答