简体   繁体   English

映射的Jackson和Hibernate异常

[英]Jackson and Hibernate exception with mapping

I have several problems with Hibernate-Spring MVC. 我在Hibernate-Spring MVC中遇到几个问题。 This is an example of my call from controller to database entity: 这是我从控制器到数据库实体的调用的一个示例:

controller 控制者

@Override
    @RequestMapping(value = { "/cars/{idFleet}"}, method = RequestMethod.GET)
    public @ResponseBody Response<List<Car>> getCars(@PathVariable int idFleet) throws QueryException{  
        return fleetAndCarService.findCarsByIdFleet(idFleet);
    }

services 服务

    @Override
//  @Transactional
    public Response<List<Car>> findCarsByIdFleet(int idFleet) throws QueryException {
        try{
            return new Response<List<Car>>(HttpStatus.OK.value(),databaseFleetsAndCarsServices.findCarsByIdFleet(idFleet));
        } catch (Exception e) {
            throw new QueryException(e);
        }
    }

database services 数据库服务

@Override
    public List<Car> findCarsByIdFleet(int idFleet) {
        return carServices.findByFleetIdFleet(idFleet);
    }

car services with named query 具有命名查询的汽车服务

@Override
@Transactional
public List<Car> findByFleetIdFleet(int idFleet) {
    return carRepository.findByFleetIdFleet(idFleet);
}

car repository 汽车资料库

public interface CarRepository extends JpaRepository<Car, Integer> {

    //Query method of spring, I put findBy and then the key of research 
    List<Car> findByFleetIdFleet(int idFleet);

}

car entity 汽车实体

@Entity

@Table(name = "car", catalog = "ATS") public class Car implements java.io.Serializable { @Table(name =“ car”,catalog =“ ATS”)公共类Car实现java.io.Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private Integer idCar;
private CarType carType;
private Fleet fleet;
private String id;
private int initialKm;
private String carChassis;
private String note;
private Set<Acquisition> acquisitions = new HashSet<Acquisition>(0);

public Car() {
}

public Car(CarType carType, Fleet fleet, int initialKm, String carChassis) {
    this.carType = carType;
    this.fleet = fleet;
    this.initialKm = initialKm;
    this.carChassis = carChassis;
}

public Car(CarType carType, Fleet fleet, String id, int initialKm, String carChassis, String note,
        Set<Acquisition> acquisitions) {
    this.carType = carType;
    this.fleet = fleet;
    this.id = id;
    this.initialKm = initialKm;
    this.carChassis = carChassis;
    this.note = note;
    this.acquisitions = acquisitions;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id_car", unique = true, nullable = false)
public Integer getIdCar() {
    return this.idCar;
}

public void setIdCar(Integer idCar) {
    this.idCar = idCar;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_carType", nullable = false)
public CarType getCarType() {
    return this.carType;
}

public void setCarType(CarType carType) {
    this.carType = carType;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_fleet", nullable = false)
public Fleet getFleet() {
    return this.fleet;
}

public void setFleet(Fleet fleet) {
    this.fleet = fleet;
}

@Column(name = "id", length = 5)
public String getId() {
    return this.id;
}

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

@Column(name = "initialKm", nullable = false)
public int getInitialKm() {
    return this.initialKm;
}

public void setInitialKm(int initialKm) {
    this.initialKm = initialKm;
}

@Column(name = "carChassis", nullable = false, length = 20)
public String getCarChassis() {
    return this.carChassis;
}

public void setCarChassis(String carChassis) {
    this.carChassis = carChassis;
}

@Column(name = "note", length = 100)
public String getNote() {
    return this.note;
}

public void setNote(String note) {
    this.note = note;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "car")
public Set<Acquisition> getAcquisitions() {
    return this.acquisitions;
}

public void setAcquisitions(Set<Acquisition> acquisitions) {
    this.acquisitions = acquisitions;
    }
}

car type (linked by foreign key ,one to many relationship) 汽车类型(通过外键链接,一对多关系)

/**
 * CarType generated by hbm2java
 */
@Entity
@Table(name = "carType", catalog = "ATS")
public class CarType implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String idCarType;
    private String note;
    private Set<Car> cars = new HashSet<Car>(0);

    public CarType() {
    }

    public CarType(String idCarType) {
        this.idCarType = idCarType;
    }

    public CarType(String idCarType, String note, Set<Car> cars) {
        this.idCarType = idCarType;
        this.note = note;
        this.cars = cars;
    }

    @Id

    @Column(name = "id_carType", unique = true, nullable = false, length = 5)
    public String getIdCarType() {
        return this.idCarType;
    }

    public void setIdCarType(String idCarType) {
        this.idCarType = idCarType;
    }

    @Column(name = "note", length = 100)
    public String getNote() {
        return this.note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "carType")
    public Set<Car> getCars() {
        return this.cars;
    }

    public void setCars(Set<Car> cars) {
        this.cars = cars;
    }

}

fleet entity 舰队实体

@Entity
@Table(name = "fleet", catalog = "ATS")
public class Fleet implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer idFleet;
    private Ecu ecu;
    private String application;
    private String cubic;
    private int power;
    private String euroClass;
    private String engineType;
    private String traction;
    private String transmission;
    private String note;
    private Set<Car> cars = new HashSet<Car>(0);

Acquisition entity 收购实体

@Entity
@Table(name = "acquisition", catalog = "ATS")
public class Acquisition implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer idAcquisition;
    private Car car;
    private DpfWeighting dpfWeighting;
    private MissionProfile missionProfile;
    private OilSample oilSample;
    private Shift shift;
    private SwVersion swVersion;
    private Date date;
    private float sessionDuration;
    private int beginKm;
    private int endKm;
    private String driverName;
    private String dataset;
    private String drChannelsConf;
    private String excelRow;
    private Set<Rdi> rdis = new HashSet<Rdi>(0);
    private Set<SelfLearning> selfLearnings = new HashSet<SelfLearning>(0);
    private Set<Iupr> iuprs = new HashSet<Iupr>(0);

I'm using maven with 4.2.1.RELEASE 4.3.11.Final 我正在将Maven与4.2.1.RELEASE 4.3.11.Final一起使用

When I call my controller I receive one exception: 当我打电话给控制器时,我收到一个异常:

com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.model.Response["body"]->java.util.ArrayList[0]->com.domain.Car["carType"]->com.domain.CarType_$$_jvst615_e["handler"]) com.fasterxml.jackson.databind.JsonMappingException:未找到类org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer的序列化器,也未发现创建BeanSerializer的属性(为避免异常,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS))(通过引用链: .model.Response [“ body”]-> java.util.ArrayList [0]-> com.domain.Car [“ carType”]-> com.domain.CarType _ $$ _ jvst615_e [“ handler”])

I would like to understand if I have to remove set variable from entity and how can I resolve this exception on mapping. 我想了解是否必须从实体中删除设置变量,以及如何解决映射上的异常。 Thanks For the moment I'm using @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) on each entity, but it is correct?Futhermore I have cicle loop into entity query (is it possible that hibernate tool wrong with write all entity or that I have seleceted the wrong way to generate entity?) 谢谢目前我在每个实体上使用@JsonIgnoreProperties({“ hibernateLazyInitializer”,“ handler”}),但这是正确的?还是我选择了错误的方式来生成实体?)

When I use repository methods like 当我使用类似的存储库方法时

@Override
@Transactional
public List<Fleet> getFleets() {
    return fleetRepository.findAll();
}

no problem, it works very well 没问题,效果很好

UPDATE : I added @JsonManagedReference on @OneToMany variable and @JsonBackReference on @ManyToOne variable and it seems to work but now in car I can see only Acquisition and not Fleet and CarType (so there was annotation with JsonBackReference) instead from query I receive all the object but carType and Fleet are null, I need the opposite, so I need fleet and carType, not acquisition This is the link where I found it Infinite Recursion with Jackson JSON and Hibernate JPA issue 更新 :我添加@JsonManagedReference@OneToMany变量和@JsonBackReference@ManyToOne变量,它似乎工作,但现在在车上我只能看到收购,而不是舰队和CarType(所以没有标注与JsonBackReference),而不是从我的查询接收所有该对象,但carType和Fleet为空,我需要相反,所以我需要Fleet和carType,而不是获取这是我在杰克逊JSON和Hibernate JPA问题中发现它的Infinite Recursion的链接

Try add @ManyToOne(fetch = FetchType.EAGER) to your Car entity - attribute carType (or method getCarType - depends on what you use). 试加@ManyToOne(fetch = FetchType.EAGER)到您的Car实体-属性carType (或方法getCarType -取决于你用什么)。 For EAGER fetch - Car entity should have entity object instead of proxy object. 对于EAGER提取- Car实体应具有实体对象而非代理对象。

It is not good practice to return entities from application, because you can't control what relations and data would be returned. 从应用程序返回实体不是一个好习惯,因为您无法控制将返回什么关系和数据。 Instead of you should return VO (value objects). 而不是您应该返回VO(值对象)。 Using VO is safe and you have control what you return from application. 使用VO是安全的,您可以控制从应用程序返回的内容。 For mappigs from entites to VO object (including relations) you can use some mapper, Orika for example. 从entites的到VO对象(包括关系),你可以使用一些映射器,mappigs Orika例如。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM