当前位置: 首页 > 知识库问答 >
问题:

.DefaultHandlerExceptionResolver我在上传数据时得到这个错误,请帮助我在这个项目中它在服务器上正常工作

谭俊
2023-03-14
package asmt1.demo.entity;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;   
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import asmt1.demo.dto.UserStatus;
//@Entity annotation specifies that the class is an entity and is mapped to a database table.
//@Table annotation specifies the name of the database table to be used for mapping
@Entity
@Table(name="Contactdetail")
public class Contact {
        //@Id is used to specify the primary key
        @Id
    //Generated value is used to generate pk value ie. id to be autogenerated and assign identity column(id)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    //@column is used to specify the column condition
    //@Column( unique = true)  
    private String firstName;   
    
    private String lastName;
    //@Column(unique = true)
    private long contactNo;
    private String mailId;
    
    //list of named constant ie. status
    @Enumerated(EnumType.STRING)
    private UserStatus status;
    
    //it is used to create one-to-one relationship between the contact and address table
    //fetch type.lazy tells Hibernate to only fetch the related entities from the database when you use the relationship
    @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinTable(name="conadd",
                joinColumns = {@JoinColumn(name="id")},
                inverseJoinColumns = {@JoinColumn(name="addid")})
    //To handle the problem related to the serialization of the model using Jackson API when the model attributes have a lazy loading defined,
    //we have to tell the serializer to ignore the chain or helpful garbage that Hibernate adds to classes, so it can manage lazy loading of data by declaring @JsonIgnoreProperties
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private Set<Address> address=new HashSet<>();

    //generate getters,setters, toString() and constructor using fields
    
    public Contact() {}
    
    public Contact(String firstName, String lastName, long contactNo, String mailId, UserStatus status,
            Set<Address> address) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.contactNo = contactNo;
        this.mailId = mailId;
        this.status = status;
        this.address = address;
    }

    public Set<Address> getAddress() {
        return address;
    }
    public void setAddress(Set<Address> address) {
        this.address = address;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public long getContactNo() {
        return contactNo;
    }
    public void setContactNo(long contactNo) {
        this.contactNo = contactNo;
    }
    public String getMailId() {
        return mailId;
    }
    public void setMailId(String mailId) {
        this.mailId = mailId;
    }
    
    public UserStatus getStatus() {
        return status;
    }

    public void setStatus(UserStatus status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Contact [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", contactNo=" + contactNo
                + ", mailId=" + mailId + "]";
    }
}
package asmt1.demo.entity;

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.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

//@Entity annotation specifies that the class is an entity and is mapped to a database table.
//@Table annotation specifies the name of the database table to be used for mapping

@Entity
@Table(name="addressDetail")
public class Address {
    //@Id is used to specify the primarykey
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long addid;
        private String street1;
        private String street2;
        private long zipcode;
        private String city;
        private String state;
        private String Country;
        //mappedby is used to specify to relationship
        @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "address")
        private Set<Contact> contact=new HashSet<>();

        //generate getters,setters, toString() and constructor using fields
        
        public long getId() {
            return addid;
        }

        public Set<Contact> getContact() {
            return contact;
        }

        public void setContact(Set<Contact> contact) {
            this.contact = contact;
        }

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

        public String getStreet1() {
            return street1;
        }

        public void setStreet1(String street1) {
            this.street1 = street1;
        }

        public String getStreet2() {
            return street2;
        }

        public void setStreet2(String street2) {
            this.street2 = street2;
        }

        public long getZipcode() {
            return zipcode;
        }

        public void setZipcode(long zipcode) {
            this.zipcode = zipcode;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getCountry() {
            return Country;
        }

        public void setCountry(String country) {
            Country = country;
        }

        public Address(String street1, String street2, long zipcode, String city, String state, String country) {
            super();
            this.street1 = street1;
            this.street2 = street2;
            this.zipcode = zipcode;
            this.city = city;
            this.state = state;
            Country = country;
        }
        public Address() {}
         
    }
package asmt1.demo.dto;

import java.util.HashSet;
import java.util.Set;

import asmt1.demo.entity.Address;
import asmt1.demo.entity.Contact;

public class AddressReq {

    
    private Set<Address> address=new HashSet<>();
    private Set<Contact> contact=new HashSet<>();


    public Set<Address> getAddress() {
        return address;
    }

    public void setAddress(Set<Address> address) {
        this.address = address;
    }

    public Set<Contact> getContact() {
        return contact;
    }

    public void setContact(Set<Contact> contact) {
        this.contact = contact;
    }
    

    public AddressReq(Set<Address> address, Set<Contact> contact) {
        super();
        this.address = address;
        this.contact = contact;
    }
    public AddressReq() {}
    @Override
    public String toString() {
        return "AddressReq [address=" + address + ", contact=" + contact + "]";
    }
}
package asmt1.demo.dto;
//constant value for userstatus class 
public enum UserStatus {
    ACTIVE,INACTIVE
}
package asmt1.demo.controller;

import java.util.List;
import java.util.NoSuchElementException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import asmt1.demo.converter.ContactConverter;
import asmt1.demo.dto.AddressReq;
import asmt1.demo.dto.ContactDto;
import asmt1.demo.entity.Contact;
import asmt1.demo.repository.AddressRepo;
import asmt1.demo.repository.ContactRepo;

//@restcontroller is used for restful services 
@RestController
//@RequestMapping is used for creating baseurl for controller will be used
@RequestMapping("/contact")
public class ContactController {

    //@Autowired will search the object of class
    @Autowired
    private ContactRepo ctrepo;
    @Autowired
    private AddressRepo addrepo;;
    @Autowired
    private ContactConverter converter;
    
    
    //@Requestbody is used to map/bind methods with pojo pr value to return value to the web
    //@postmapping is used to add data to database from web
    @PostMapping("/add")
    public List<Contact> newcontact(@RequestBody AddressReq req) {
         return ctrepo.saveAll(req.getContact());
    }
    
    //@getmapping is used to get the details/records from database on web page
    @GetMapping("/contactlist")
    public List<Contact> getcontactlist(){
        return ctrepo.findAll(Sort.by(Sort.Direction.ASC, "firstName","lastName"));
    }
    @GetMapping("/contactdto")
    public List<ContactDto> getcontactlistdto(){
        List<Contact> findAll=ctrepo.findAll();
        return converter.entitytodto(findAll);
    }
    @GetMapping("/contactlist/{id}")
    public ResponseEntity<Contact> get(@PathVariable Long id) {
        try {
           Contact contact = ctrepo.getOne(id);
            return new ResponseEntity<Contact>(contact, HttpStatus.OK);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<Contact>(HttpStatus.NOT_FOUND);
        }      
    }
    @GetMapping("/contactdto/{id}")
    public ContactDto getbyid(@PathVariable Long id) {
           Contact orElse=ctrepo.findById(id).orElse(null);
           return converter.entitytodto(orElse);
    }
    
    @GetMapping("/orderlist")
    public List<Contact> getcontactlistbyorder(){
        return ctrepo.findAllByOrderByIdDesc();
    }
    
    @PostMapping("/save")
    public ContactDto savedto(@RequestBody ContactDto dto) {
        Contact contact=converter.dtotoentity(dto);
        contact=ctrepo.save(contact);
        return converter.entitytodto(contact);
    }
    
    
    //@deletemapping is used to delete the records/details from database by web page
    @DeleteMapping("/delete/{id}")
    public String deletebyid(@PathVariable long id){
        if (ctrepo.findById(id)==null) {
            return "Id not found.....Please enter correct id";
        }
         ctrepo.deleteById(id);
         return "Successfully deleted "+id;
    }
    
    //@putmapping is used to change/update the records/details in database by web page
    @PutMapping("/edit")
    public List<Contact> editcontactbyid(@RequestBody AddressReq req ){
        return ctrepo.saveAll(req.getContact());
    }
}

下面是我上传数据的Json格式,但它显示了错误,即在[source:(PushbackInputStream);line:1,column:2]]2021-05-04 12:57:07.799 WARN 876----[nio-9090-exec-4].W.S.M.S.DefaultHandlerExceptionResolver:Resolved[org.springframework.http.converter.HttpMessageNotreadableException:Json parse error:不能将嵌套异常是com.fasterxml.jackson.databind.exc.MismatchedInputException:无法将java.util.hashset 的实例反序列化出START_OBJECT令牌[source:(PushbackInputStream);行:1,列:13](通过引用链:asmt1.demo.dto.addressReq[“contact”])]

 {"contact":{
    "firstName":"tomu",
    "lastName":"shawn",
    "contactNo":9124245,
    "mailId":"ggia@gmail.com",
    "status":"INACTIVE",
    "address":{
        "street1":"A/wing-24",
        "street2":"plotno-4",
        "city":"Mumbai",
        "state":"Maharashtra",
        "country":"India",
        "zipcode":705
    }}}

共有1个答案

刘泰
2023-03-14

在您的AddressReqContact中设置为集合,但在您的pay load中,您发送的是Object,它应该是Object的集合。

基于AddressReq类,负载应该是

{["contact":{
    "firstName":"tomu",
    "lastName":"shawn",
    "contactNo":9124245,
    "mailId":"ggia@gmail.com",
    "status":"INACTIVE",
    "address":{
        "street1":"A/wing-24",
        "street2":"plotno-4",
        "city":"Mumbai",
        "state":"Maharashtra",
        "country":"India",
        "zipcode":705
    }
  }]
}

或者,如果您的请求始终是联系人的单个条目,则可以将联系人属性更改为单个实例,而不是contact实例的集合

 类似资料: