Prezados, Tenho um modelo que tem dois relacionamentos unidirecional @many. Quando recupero a informação na tela de edição e vou salvar para atualizar as infromações recebo o lazyinitialization excepion. O problema que não consigo colocar os dois relacionamentos como eager. Já tentei algumas coisas que pesquisei na net mas sem sucesso. Poderiam me orientar para resolver este problema?
insira seu código aqui
```package br.com.intranet.entities;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ViewScoped;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
import br.com.intranet.enun.PriorityBudget;
import br.com.intranet.enun.ProductBudget;
import br.com.intranet.interfacies.ConverterEntity;
@Entity
@ViewScoped
public class Budget implements Serializable, ConverterEntity {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "SEQ_BUDGET", sequenceName = "SEQ_BUDGET_TABLE", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_BUDGET")
private long id;
private long sdo;
@Size(max = 3)
private String office;
@NotNull(message = "#{messages.messageFieldVersionObrigatory}")
private int version;
@Temporal(TemporalType.TIMESTAMP)
private Date openDate;
@Enumerated(EnumType.STRING)
private ProductBudget product;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "client_id")
private Client client;
@NotBlank(message="#{messages.messageFieldProjectCarObrigatory}")
@Size(min=1, max=255, message="#{messages.messageFieldLenghtValid255}")
private String projectCar;
@Temporal(TemporalType.TIMESTAMP)
private Date dateCustomerResponse;
@Enumerated(EnumType.STRING)
private PriorityBudget priority;
@Size(max = 7)
private String codeRequester;
@Size(max = 255)
private String nameRequester;
@Size(max = 7)
private String codeResponsible;
@Size(max = 255)
private String nameResponsible;
@Size(max = 255)
private String process;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name="BUDGET_HAS_COMPANY", joinColumns={@JoinColumn(name="BUDGET_ID", referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="COMPANY_ID", referencedColumnName="id")})
private List<Company> company;
@Column(columnDefinition = "TEXT")
private String comments;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "procedure_id")
private Procedure procedure;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "itensCheck_id")
private ItensCheck itensCheck;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "localDelivery_id")
private LocalDelivery localDelivery;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "budget_id")
private List<Drawing> drawing;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "status_id")
private Status status;
private Integer timeBudget;
private Integer timevalorization;
@Size(max = 255)
private String manager;
@Transient
private Integer timeAll;
@Transient
private String yearSdo;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getSdo() {
return sdo;
}
public void setSdo(long sdo) {
this.sdo = sdo;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Date getOpenDate() {
return openDate;
}
public void setOpenDate(Date openDate) {
this.openDate = openDate;
}
public ProductBudget getProduct() {
return product;
}
public void setProduct(ProductBudget product) {
this.product = product;
}
public ProductBudget[] getProductBudget() {
return product.values();
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public String getProjectCar() {
return projectCar;
}
public void setProjectCar(String projectCar) {
this.projectCar = projectCar;
}
public Date getDateCustomerResponse() {
return dateCustomerResponse;
}
public void setDateCustomerResponse(Date dateCustomerResponse) {
this.dateCustomerResponse = dateCustomerResponse;
}
public PriorityBudget getPriority() {
return priority;
}
public void setPriority(PriorityBudget priority) {
this.priority = priority;
}
public PriorityBudget[] getPriorityBudget() {
return priority.values();
}
public String getCodeRequester() {
return codeRequester;
}
public void setCodeRequester(String codeRequester) {
this.codeRequester = codeRequester;
}
public String getNameRequester() {
return nameRequester;
}
public void setNameRequester(String nameRequester) {
this.nameRequester = nameRequester;
}
public String getCodeResponsible() {
return codeResponsible;
}
public void setCodeResponsible(String codeResponsible) {
this.codeResponsible = codeResponsible;
}
public String getNameResponsible() {
return nameResponsible;
}
public void setNameResponsible(String nameResponsible) {
this.nameResponsible = nameResponsible;
}
public String getProcess() {
return process;
}
public void setProcess(String process) {
this.process = process;
}
public List<Company> getCompany() {
return company;
}
public void setCompany(List<Company> company) {
this.company = company;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Procedure getProcedure() {
return procedure;
}
public void setProcedure(Procedure procedure) {
this.procedure = procedure;
}
public ItensCheck getItensCheck() {
return itensCheck;
}
public void setItensCheck(ItensCheck itensCheck) {
this.itensCheck = itensCheck;
}
public LocalDelivery getLocalDelivery() {
return localDelivery;
}
public void setLocalDelivery(LocalDelivery localDelivery) {
this.localDelivery = localDelivery;
}
public List<Drawing> getDrawing() {
return drawing;
}
public void setDrawing(List<Drawing> drawing) {
this.drawing = drawing;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
public Integer getTimeBudget() {
return timeBudget;
}
public void setTimeBudget(Integer timeBudget) {
this.timeBudget = timeBudget;
}
public Integer getTimevalorization() {
return timevalorization;
}
public void setTimevalorization(Integer timevalorization) {
this.timevalorization = timevalorization;
}
public Integer getTimeAll() {
timeBudget = (timeBudget == null) ? 0 : timeBudget;
timevalorization = (timevalorization == null) ? 0 : timevalorization;
return timeBudget + timevalorization;
}
public String getNumberSdo() {
SimpleDateFormat format = new SimpleDateFormat("yy");
String year = format.format(openDate).toString();
return office + "-" + year + "-" + sdo;
}
}
package br.com.intranet.controllers;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import br.com.intranet.classes.User;
import br.com.intranet.dao.BudgetDao;
import br.com.intranet.dao.ClientDao;
import br.com.intranet.dao.CompanyDao;
import br.com.intranet.dao.FeasibilityDao;
import br.com.intranet.dao.HistoricDao;
import br.com.intranet.dao.StatusDao;
import br.com.intranet.entities.Budget;
import br.com.intranet.entities.Client;
import br.com.intranet.entities.Company;
import br.com.intranet.entities.Drawing;
import br.com.intranet.entities.Historic;
import br.com.intranet.entities.ItensCheck;
import br.com.intranet.entities.LocalDelivery;
import br.com.intranet.entities.Procedure;
import br.com.intranet.entities.Status;
import br.com.intranet.util.MessageEmail;
import br.com.intranet.util.SendMail;
@ManagedBean
@ViewScoped
public class BudgetBean implements Serializable {
private static final long serialVersionUID = 1L;
private Budget budget;
private List<Client> clients;
private List<Company> companies;
private String screen;
private FacesContext facesContext = FacesContext.getCurrentInstance();
private BudgetDao budgetDao = new BudgetDao();
private ClientDao clientDao = new ClientDao();
private CompanyDao companyDao = new CompanyDao();
private StatusDao statusDao = new StatusDao();
private HistoricDao historicDao = new HistoricDao();
private FeasibilityDao feasibilityDao = new FeasibilityDao();
@PostConstruct
public void init() {
long id = Integer.parseInt(facesContext.getExternalContext().getRequestParameterMap().get("budget_id"));
screen = facesContext.getExternalContext().getRequestParameterMap().get("screen");
if(id == 0){
User user = getUser();
budget = new Budget();
Status status = statusDao.getStatusById(1);
budget.setStatus(status);
budget.setOpenDate(new Date());
budget.setVersion(1);
budget.setOffice(getManufacturesGroup(user.getUnidade()));
budget.setCodeRequester(user.getLoginUsuario());
budget.setNameRequester(user.getNomeCompleto());
budget.setCodeResponsible(user.getLoginUsuario());
budget.setNameResponsible(user.getNomeCompleto());
if(budget.getDrawing() == null){
budget.setDrawing(new ArrayList<Drawing>());
}
budget.setItensCheck(new ItensCheck());
budget.setLocalDelivery(new LocalDelivery());
budget.setProcedure(new Procedure());
} else {
budget = budgetDao.getBudgetById(id);
}
}
private String getManufacturesGroup(String manufactures) {
String result = "AE";
if(manufactures.toLowerCase().equals("cedep")) {
result = "CE";
} else if(manufactures.toLowerCase().equals("vesta")) {
result = "VE";
} else if(manufactures.toLowerCase().equals("flamma")) {
result = "FL";
} else if(manufactures.toLowerCase().equals("tec")) {
result = "TE";
}
return result;
}
private User getUser() {
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
return (User) session.getAttribute("userLogged");
}
public void addNewDrawing() {
int row = budget.getDrawing().size();
Drawing drawing = new Drawing();
budget.getDrawing().add(row, drawing);
}
public void removeNewDrawing(Object drawing) {
//budget.getDrawing().remove(drawing);
}
public void saveBudget(Budget budget) {
boolean save = budgetDao.save(budget, screen);
if(save && screen.equals("new")) {
String folder = "W:/TI/Tmp/" + budget.getSdo() + "-" + budget.getVersion();
File fileFolder = new File(folder);
fileFolder.mkdir();
registerHistorics(budget);
}
}
public void registerHistorics(Budget budget) {
Historic historic = new Historic();
historic.setBudgeId(budget.getSdo());
historic.setComments("Aberto com sucesso");
historic.setDate(budget.getOpenDate());
historic.setUsercode(budget.getCodeRequester());
historic.setUsername(budget.getNameRequester());
historic.setStatus(budget.getStatus());
historicDao.save(historic);
MessageEmail message = new MessageEmail();
String body = message.messageEmailSdo(budget);
String subject = "#[" + budget.getSdo() + "] - Abertura de novo orçamento";
SendMail mail = new SendMail();
try {
mail.sendEmail("eduardo.souza@aethra.com.br", subject, body); //sdo.vendas@aethra.com.br
} catch (IOException e) {
e.printStackTrace();
}
}
public Budget getBudget() {
return budget;
}
public void setBudget(Budget budget) {
this.budget = budget;
}
public List<Client> getClients() {
clients = clientDao.getAllClients();
return clients;
}
public void setClients(List<Client> clients) {
this.clients = clients;
}
public List<Company> getCompanies() {
companies = companyDao.getAllCompanies();
return companies;
}
public void setCompanies(List<Company> companies) {
this.companies = companies;
}
public boolean getEnableNewDrawing() {
return (budget.getId() == 0 || (screen.equals("modify") && budget.getStatus().getId() == 1)) ? true : false;
}
public boolean getEnableSaveBudget() {
return (budget.getId() == 0 || (screen.equals("modify") && budget.getStatus().getId() == 1)) ? true : false;
}
}
package br.com.intranet.dao;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import br.com.intranet.classes.User;
import br.com.intranet.entities.Budget;
import br.com.intranet.entities.Feasibility;
import br.com.intranet.entities.Status;
import br.com.intranet.persistence.JpaUtil;
public class BudgetDao implements Serializable {
private static final long serialVersionUID = 1L;
@PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager em = JpaUtil.getEntityManager();
public boolean save(Budget budget, String screen) {
FacesMessage msg;
boolean save;
em.getTransaction().begin();
try {
em.persist(budget);
if(screen.equals("new")) {
budget.setSdo(budget.getId());
em.persist(budget);
}
em.flush();
em.getTransaction().commit();
save = true;
msg = new FacesMessage("Salvo com Sucesso.");
} catch(Exception e) {
em.getTransaction().rollback();
save = false;
msg = new FacesMessage(e.getMessage());
}
FacesContext.getCurrentInstance().addMessage(null, msg);
return save;
}
public String getResponsibleBudgetById(long budgetId) {
String jpqlPendencies = "select b from Budget b where b.id = " + budgetId;
Budget budget = JpaUtil.getEntityManager().createQuery(jpqlPendencies, Budget.class).getSingleResult();
return budget.getCodeResponsible();
}
public Budget getBudgetById(long budgetId) {
String jpqlBudget = "select b from Budget b " +
"join fetch b.drawing d " +
"where b.id = " + budgetId;
Budget budget = em.createQuery(jpqlBudget, Budget.class).getSingleResult();
budget.setDrawing(budget.getDrawing());
return budget;
}
public boolean updateBudget(long id, Status status, Feasibility feasibility, User user, Integer timeBudget) {
boolean save;
Budget budget = em.find(Budget.class, id);
em.getTransaction().begin();
try {
if(status.getId() == 2 || status.getId() == 3) {
budget.setCodeResponsible(feasibility.getUserCode());
budget.setNameResponsible(feasibility.getUserName());
if(status.getId() == 3) {
budget.setTimeBudget(timeBudget);
}
}
if(status.getId() == 4) {
budget.setCodeResponsible(budget.getCodeRequester());
budget.setNameResponsible(budget.getNameRequester());
}
if(status.getId() == 7) {
budget.setTimevalorization(timeBudget);
budget.setCodeResponsible(budget.getCodeRequester());
budget.setNameResponsible(budget.getNameRequester());
}
else {
budget.setCodeResponsible(user.getLoginUsuario());
budget.setNameResponsible(user.getNomeCompleto());
}
budget.setStatus(status);
em.getTransaction().commit();
save = true;
} catch(Exception e) {
em.getTransaction().rollback();
save = false;
}
return save;
}
}
insira seu código aqui ```<!DOCTYPE html>
insira seu código aqui
```<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="postgres" transaction-type="RESOURCE_LOCAL">
<class>br.com.intranet.entities.Budget</class>
<class>br.com.intranet.entities.Status</class>
<class>br.com.intranet.entities.Client</class>
<class>br.com.intranet.entities.Company</class>
<class>br.com.intranet.entities.Drawing</class>
<class>br.com.intranet.entities.LocalDelivery</class>
<class>br.com.intranet.entities.Procedure</class>
<class>br.com.intranet.entities.ItensCheck</class>
<class>br.com.intranet.entities.Pendency</class>
<class>br.com.intranet.entities.Historic</class>
<class>br.com.intranet.entities.CheckBudget</class>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>AUTO</validation-mode>
<properties >
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="sgi"/>
<property name="javax.persistence.jdbc.password" value="sgilinux"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://10.10.0.15:5432/sdo"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties >
</persistence-unit >
</persistence>