0

I have fetched a list of objects of type Company from the database. But when trying to serialize the list using Jackson to JSON, throws an error

 com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.zerosolutions.repository.entity.CompanySector.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.zerosolutions.repository.entity.Company["sector"]->com.zerosolutions.repository.entity.CompanySector["companies"])

Company:

@Entity
@Table(name = "company")
public class Company {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "name")
private String name;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "sector")
private CompanySector sector;

@OneToOne
@JoinColumn(name = "id")
private CompanyProfile profile;

@OneToOne
@JoinColumn(name = "id")
private CompanyAddress address;

@OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
private List<Job> jobs = new ArrayList<>();

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public CompanySector getSector() {
    return sector;
}

public void setSector(CompanySector sector) {
    this.sector = sector;
}

public CompanyProfile getProfile() {
    return profile;
}

public void setProfile(CompanyProfile profile) {
    this.profile = profile;
}

public CompanyAddress getAddress() {
    return address;
}

public void setAddress(CompanyAddress address) {
    this.address = address;
}

public List<Job> getJobs() {
    return jobs;
}

public void setJobs(List<Job> jobs) {
    this.jobs = jobs;
}   

}

CompanySector:

@Entity
@Table(name = "sectors")
public class CompanySector {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

@Column(name="sector")
private String sector;


@OneToMany(mappedBy="sector", cascade=CascadeType.PERSIST)
private List<Company> companies = new ArrayList<>();

public int getId() {
    return id;
}

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

public String getSector() {
    return sector;
}

public void setSector(String sector) {
    this.sector = sector;
}

public List<Company> getCompanies() {
    return companies;
}

}

Conversion code:

@RequestMapping(value = "/getCompanyList", method = RequestMethod.GET,  produces={ "application/json"})
public @ResponseBody String getCompanyList() {

    ObjectMapper mapper = new ObjectMapper();
    try {
        List<Company> companyList = companyServices.getCompanyList();
        String companyListString = mapper.writeValueAsString(companyList); // this line throws error        
        return companyListString;
    } catch (JsonProcessingException e) {
        logger.error(e);
        return null;
    }
}

Any Suggestions what might be wrong here ?

Fetching list:

public List<Company> getCompanyList(){

    Session session = sessionFactory.openSession();
    Transaction tx = null;

    try{
        tx = session.beginTransaction();
        List<Company> companies = session.createCriteria(Company.class).list();
        logger.debug(companies);
        tx.commit();
        System.out.println("companies fetched");
        return companies;
    } catch(Exception e){
        logger.error("Exceptino thrown: " + e);
        tx.rollback();
        return null;
    } finally{
        session.close();
    }
}
Meena Chaudhary
  • 6,515
  • 8
  • 40
  • 70

1 Answers1

0

If you know that you'll want to see all Companies every time you retrieve a CompanySector then change your field mapping for Companies to:

@OneToMany(fetch = FetchType.EAGER, mappedBy="sector", cascade=CascadeType.PERSIST)
private List<Company> companies = new ArrayList<>();

Another approach use Hibernate.initialize :

Hibernate.initialize(companySector.getCompany());

Also see this link it's very helpful

Community
  • 1
  • 1
karim mohsen
  • 2,051
  • 1
  • 11
  • 18