API Springboot中的映射遇到问题

时间:2015-11-16 19:20:48

标签: javascript java json angularjs spring-boot

我在springboot API中进行POST操作时遇到问题,GET运行正常,而且简单类的POST也很好。

继承我的Java控制器:

    package ar.gob.snr.gestion.incidente.controller;

    import java.util.List;

    import javax.inject.Inject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;

    import ar.gob.snr.gestion.incidente.domain.dao.IncidenteRepository;
    import ar.gob.snr.gestion.incidente.domain.model.Incidente;
    import ar.gob.snr.gestion.incidente.domain.service.IncidenteService;

    @RestController
    public class IncidenteController {

        @Autowired
        IncidenteRepository incidenteRepository;

        @Autowired
        private final IncidenteService incidenteService;

        @Inject
        public IncidenteController(final IncidenteService incidenteService) {
            this.incidenteService = incidenteService;// Inject a IncidenteService
                                                        // codigo en POM
        }

        @RequestMapping(value = "/get/incidente/{codename}", method = RequestMethod.GET)
        @ResponseBody
        public Object queryIncidente(@PathVariable String codename) {
            Incidente incidente = incidenteService.getIncidente(codename);
            if (incidente == null)
                return "No encontrado";
            return incidente;
        }

        @RequestMapping(value = "/get/incidente/", method = RequestMethod.GET)
        @ResponseBody
        public Object queryIncidente() {
            List<Incidente> incidenteL = incidenteRepository.findAll();
            return incidenteL;
        }

        @RequestMapping(value = "/set/incidente/", method = RequestMethod.POST)
        @Transactional
        public Incidente editIncidente(final @RequestBody Incidente incidente) {
            return incidenteRepository.save(incidente);
        }

    }

这似乎很有效。

而且我遇到了麻烦:

            package ar.gob.snr.gestion.incidente.domain.model;

    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;

    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    import org.apache.commons.lang3.builder.EqualsBuilder;
    import org.apache.commons.lang3.builder.HashCodeBuilder;
    import org.apache.commons.lang3.builder.ToStringBuilder;
    import com.fasterxml.jackson.annotation.JsonManagedReference;

    @Entity
    @Table(name = "incidente")
    public class Incidente implements Serializable {

        private static final long serialVersionUID = 1L;
        private Integer id;
        private String estado; // estado del incidente
        private String aperturafecha;// Fecha de Apertura del incidente
        private String aperturahora;// Hora de Apertura del incidente
        private String clasificacion;// Clasificacion del incidente
        private String diagnostico;// Diagnostico del incidente
        private String resolucion;// Resolucion del incidente
        private String insumos;// Insumos ocupados en la resolucion del incidente
        private String cierrefecha;// Fecha de cierre del incidente
        private String cierrehora;// Hora de cierre del incidente
        private String prioridad;// Prioridad del incidente
        private String indisponibilidad;// Tiempo de Indisponibilidad del incidente
        private String codename;// Nombre en codigo del incidente
        private String tipoincidente; // Tipo del incidente
        private Set<IncidenteHardwares> hardwares = new HashSet<IncidenteHardwares>();// Sistemas
                                                                                        // afectado
                                                                                        // por
                                                                                        // el
                                                                                        // incidentes
        private Set<IncidenteSistemas> sistemas = new HashSet<IncidenteSistemas>();// Hardware
                                                                                    // afectado
                                                                                    // por
                                                                                    // el
                                                                                    // incidente
        private Set<IncidenteSoftwares> softwares = new HashSet<IncidenteSoftwares>();// Software
                                                                                        // afectado
                                                                                        // por
                                                                                        // el
                                                                                        // incidente

        private Tecnico tecnico;// Tecnico afectado por el incidente

        @Id
        @GeneratedValue
        @Column(name = "incidenteid")
        public Integer getId() {
            return id;
        }

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

        // @NotFound(action=NotFoundAction.IGNORE) tener en cuenta si llegara a
        // fallar pro encontrar valores vacios
        @JsonManagedReference // JsonManagedReference Inicia la llamada (managed)
                                // mata los loops xD
        @OneToMany(fetch = FetchType.EAGER, mappedBy = "incidente", cascade = CascadeType.ALL)
        public Set<IncidenteHardwares> getHardwares() {
            return hardwares;
        }

        public void setHardwares(Set<IncidenteHardwares> hardwares) {
            this.hardwares = hardwares;
        }

        @JsonManagedReference // JsonManagedReference Inicia la llamada (managed)
                                // mata los loops xD
        @OneToMany(fetch = FetchType.EAGER, mappedBy = "incidente", cascade = CascadeType.ALL)
        public Set<IncidenteSistemas> getSistemas() {
            return sistemas;
        }

        public void setSistemas(Set<IncidenteSistemas> sistemas) {
            this.sistemas = sistemas;
        }

        @JsonManagedReference // JsonManagedReference Inicia la llamada (managed)
                                // mata los loops xD
        @OneToMany(fetch = FetchType.EAGER, mappedBy = "incidente", cascade = CascadeType.ALL)
        public Set<IncidenteSoftwares> getSoftwares() {
            return softwares;
        }

        public void setSoftwares(Set<IncidenteSoftwares> softwares) {
            this.softwares = softwares;
        }

        @Column(name = "aperturafecha")
        public String getAperturafecha() {
            return aperturafecha;
        }

        public void setAperturafecha(String aperturafecha) {
            this.aperturafecha = aperturafecha;
        }

        @Column(name = "aperturahora")
        public String getAperturahora() {
            return aperturahora;
        }

        public void setAperturahora(String aperturahora) {
            this.aperturahora = aperturahora;
        }

        @Column(name = "clasificacion")
        public String getClasificacion() {
            return clasificacion;
        }

        public void setClasificacion(String clasificacion) {
            this.clasificacion = clasificacion;
        }

        @ManyToOne
        @JoinColumn(name = "tecnico", referencedColumnName = "tecnicoid")
        public Tecnico getTecnico() {
            return tecnico;
        }

        public void setTecnico(Tecnico tecnico) {
            this.tecnico = tecnico;
        }

        @Column(name = "diagnostico")
        public String getDiagnostico() {
            return diagnostico;
        }

        public void setDiagnostico(String diagnostico) {
            this.diagnostico = diagnostico;
        }

        @Column(name = "resolucion")
        public String getResolucion() {
            return resolucion;
        }

        public void setResolucion(String resolucion) {
            this.resolucion = resolucion;
        }

        @Column(name = "insumos")
        public String getInsumos() {
            return insumos;
        }

        public void setInsumos(String insumos) {
            this.insumos = insumos;
        }

        @Column(name = "cierrefecha")
        public String getCierrefecha() {
            return cierrefecha;
        }

        public void setCierrefecha(String cierrefecha) {
            this.cierrefecha = cierrefecha;
        }

        @Column(name = "cierrehora")
        public String getCierrehora() {
            return cierrehora;
        }

        public void setCierrehora(String cierrehora) {
            this.cierrehora = cierrehora;
        }

        @Column(name = "prioridad")
        public String getPrioridad() {
            return prioridad;
        }

        public void setPrioridad(String prioridad) {
            this.prioridad = prioridad;
        }

        @Column(name = "indisponibilidad")
        public String getIndisponibilidad() {
            return indisponibilidad;
        }

        public void setIndisponibilidad(String indisponibilidad) {
            this.indisponibilidad = indisponibilidad;
        }

        @Column(name = "codename")
        public String getCodename() {
            return codename;
        }

        public void setCodename(String codename) {
            this.codename = codename;
        }

        @Column(name = "tipoincidente")
        public String getTipoincidente() {
            return tipoincidente;
        }

        public void setTipoincidente(String tipoincidente) {
            this.tipoincidente = tipoincidente;
        }

        @Column(name = "estado")
        public String getEstado() {
            return estado;
        }

        public void setEstado(String estado) {
            this.estado = estado;
        }

        @Override
        public boolean equals(Object value) {
            if (this == value) {
                return true;
            }
            if (value instanceof Incidente == false)
                return false;
            Incidente rhs = (Incidente) value;
            return new EqualsBuilder().append(codename, rhs.codename).isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37).append(codename).toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this).append("codename", codename).toString();
        }

    }

这个类我试图更新/添加一个新项目,问题在于:

        private Set<IncidenteHardwares> hardwares = new HashSet<IncidenteHardwares>();
        private Set<IncidenteSistemas> sistemas = new HashSet<IncidenteSistemas>();
        private Set<IncidenteSoftwares> softwares = new HashSet<IncidenteSoftwares>();

我似乎无法在使用这些对象时使POST工作,它们是对关联表的引用,该关联表链接IncidenteID和Software / Sistema / HardwareID以获取数组。

澄清代码:

         package ar.gob.snr.gestion.incidente.domain.model;

    import java.io.Serializable;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinColumns;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    import org.springframework.data.rest.core.annotation.RestResource;

    import com.fasterxml.jackson.annotation.JsonBackReference;

    @Entity
    @Table(name = "hardxsoft")
    public class HardwareSoftwares implements Serializable {

        private static final long serialVersionUID = 1L;
        private HardwareSoftwaresPK id;
        private Hardware hardware;
        private Software software;

        @EmbeddedId
        public HardwareSoftwaresPK getId() {
            return id;
        }

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

        @JsonBackReference
        @RestResource(exported = true)
        @ManyToOne(fetch = FetchType.EAGER, targetEntity = Hardware.class, optional = true)
        @JoinColumns(value = {
                @JoinColumn(name = "hardwareid", referencedColumnName = "hardwareid", insertable = false, updatable = false, nullable = false) })
        public Hardware getHardware() {
            return hardware;
        }

        public void setHardware(Hardware hardware) {
            this.hardware = hardware;
        }

        @JsonBackReference
        @RestResource(exported = true)
        @ManyToOne(fetch = FetchType.EAGER, targetEntity = Software.class, optional = true)
        @JoinColumns(value = {
                @JoinColumn(name = "softwareid", referencedColumnName = "softwareid", insertable = false, updatable = false, nullable = false) })
        public Software getSoftware() {
            return software;
        }

        public void setSoftware(Software software) {
            this.software = software;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            HardwareSoftwares other = (HardwareSoftwares) obj;
            if (id == null) {
                if (other.id != null)
                    return false;
            } else if (!id.equals(other.id))
                return false;
            return true;
        }

        @Override
        public String toString() {
            return "HardwareSoftwares [hardware=" + hardware + ", software=" + software + "]";
        }

    }



                package ar.gob.snr.gestion.incidente.domain.model;

            import java.io.Serializable;

            import javax.persistence.Column;
            import javax.persistence.Embeddable;

            import org.apache.commons.lang3.builder.EqualsBuilder;
            import org.apache.commons.lang3.builder.HashCodeBuilder;

            @Embeddable
            public class HardwareSoftwaresPK implements Serializable {

                private static final long serialVersionUID = 1L;
                private Integer hardwareid;
                private Integer softwareid;

                public HardwareSoftwaresPK() {
                    super();
                }

                public HardwareSoftwaresPK(String source) {
                    int softwareIndice = source.indexOf("-");
                    softwareid = Integer.valueOf(source.substring(0, softwareIndice));
                    hardwareid = Integer.valueOf(source.substring(softwareIndice + 1));

                }

                @Column(name = "softwareid", nullable = false)
                public Integer getSoftwareid() {
                    return softwareid;
                }

                public void setSoftwareid(Integer softwareid) {
                    this.softwareid = softwareid;
                }

                @Column(name = "hardwareid", nullable = false)
                public Integer getHardwareid() {
                    return hardwareid;
                }

                public void setHardwareid(Integer hardwareid) {
                    this.hardwareid = hardwareid;
                }

                @Override
                public boolean equals(Object value) {
                    if (this == value) {
                        return true;
                    }
                    if (value instanceof HardwareSoftwaresPK == false)
                        return false;
                    HardwareSoftwaresPK rhs = (HardwareSoftwaresPK) value;
                    return new EqualsBuilder().append(softwareid, rhs.softwareid).append(hardwareid, rhs.hardwareid).isEquals();
                }

                @Override
                public int hashCode() {
                    return new HashCodeBuilder(17, 37).append(softwareid).append(hardwareid).toHashCode();
                }

                @Override
                public String toString() {
                    return softwareid.toString().concat("-").concat(this.hardwareid.toString());
                }

            }

以下是我收到的错误消息:Error我发布的JSON数组的格式似乎不受支持,如果我评论这些对象,一切正常。

编辑:我已经解决了这个问题,在某行的某个角度/ browser / javascrip正在将我的对象从json转换为javascript,因此post方法变得无效,因为我需要发布一个json对象。

Image for the javascript object

1 个答案:

答案 0 :(得分:0)

我最终只为查询创建了两个java clases,另一个用于编写数据,我稍后会发布代码。