LazyInitializationException on SelectManyMenu in PrimeFaces CellEditor (Seam3, JSF 2.1)
***Summary***: When editing a row in a dataTable, I encounter a LazyInitializationException for a @ManyToMany relation that is editable with a PrimeFaces SelectManyMenu. My bean is @ConversationScoped and I'm using seam managed persistence contexts (as far as I can tell).

---

***Environment***:
JBoss AS 7.1.1.Final (Hibernate Core 4.0.1.Final, Mojarra 2.1.7), PostgreSQL 8.4, Primefaces 3.2, Seam 3.1.0.Final, Richfaces 4.1.0.Final, Maven 3.0.3, Java 1.7

***Disclaimer***: I'm quite new to JavaEE programming, Seam3 and all that stuff.

***Details***:
I'm trying to create a simple jsf page that lets the user create and edit Project objects. A Project is an entity that is mainly related to two other entities: ProjectParticipation and ProjectRole. A ProjectParticipation assigns an employee to a Project (and also specifies the ProjectRoles the employee is responsible for), which is a bi-directional OneToMany relation to Project. A ProjectRole is uni-directionally bound to Project and a ManyToMany relation.

At this stage of the project I'm not at all concerned about the performance of the application (and it most probably won't be an issue in the final application). Before introducing ProjectRole, I used FetchType.EAGER for the List of ProjectParticipations referenced in Project and this worked well. But apparently JPA/Hibernate is not able to fetch two Collections eagerly, so I had to switch to lazy fetching (I really don't care about this).

I created a simple JSF page that shows all Projects in a PrimeFaces dataTable which uses the in-cell editing feature. This all worked well until I added a PrimeFaces selectManyMenu (I also tried to replace it by a standard jsf selectManyMenu) for editing the association to ProjectRoles. It displays the state from the database correctly, but once I try to submit the new (or unedited) values, I run into a LazyInitializationException (see below). My Bean is @ConversationScoped (I'm starting the conversation on page load in f:metadata with s:viewAction and verified it is active throughout the editing), I'm also using seam managed persistence as far as I can tell (it's configured as described in the tutorials). As far as I understand it that should protect me from LIEs, but it seems no matter what I try I can't get it to work - and I don't even remotely understand where and why the Exception happens.

I'm not sure if a converter could help - but at least Seam's own s:objectConverter doesn't change anything at all when placed inside the selectManyMenu.

---

***The exception***:

        17:26:09,820 INFO  [javax.enterprise.resource.webcontainer.jsf.context] (http--127.0.0.1-8080-2) org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed
    	at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:393) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:385) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:378) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.AbstractPersistentCollection.write(AbstractPersistentCollection.java:208) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.PersistentList.add(PersistentList.java:163) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValuesForModel(MenuRenderer.java:382) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValue(MenuRenderer.java:129) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:315) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at org.primefaces.component.selectmanymenu.SelectManyMenuRenderer.getConvertedValue(SelectManyMenuRenderer.java:33) [primefaces-3.2.jar:]
    	at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIInput.validate(UIInput.java:960) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIInput.executeValidate(UIInput.java:1233) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIInput.processValidators(UIInput.java:698) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1612) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIData.visitRows(UIData.java:2138) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIData.visitTree(UIData.java:1437) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIForm.visitTree(UIForm.java:371) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    	at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:126) [prettyfaces-jsf2-3.3.2.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:840) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:622) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:560) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:488) [jbossweb-7.0.13.Final.jar:]
    	at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118) [prettyfaces-jsf2-3.3.2.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
    	at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
    	at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
    	at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_03-icedtea]

***The jsf page (shortened)***:

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
                    xmlns:ui="http://java.sun.com/jsf/facelets"
                    xmlns:f="http://java.sun.com/jsf/core"
                    xmlns:h="http://java.sun.com/jsf/html"
                    xmlns:pretty="http://ocpsoft.com/prettyfaces"
    				xmlns:prime="http://primefaces.org/ui" 
                    xmlns:s="http://jboss.org/seam/faces"
                    template="/WEB-INF/layout/template.xhtml">
    
    	<f:metadata>
    		<s:viewAction action="#{projectController.beginConversation()}"/>
    		<!--<s:viewAction action="#{projectHome.wire}"/>-->
    		<!-- next line is quite probably useless -->
    		<!--<s:viewAction action="#{projectRoleHome.wire}"/>-->
    	</f:metadata>
    
        <ui:define name="content">
            <div class="section">
    
                <h1>#{bundles.messages.projects}</h1>
    
                <p>#{bundles.messages.projects_intro}</p>
    
               
                <h:panelGroup rendered="#{identity.loggedIn}">
                	<p>
    		            <!--<span class="errors">
    	               		<h:messages errorClass="error" styleClass="messages" id="messages" globalOnly="true"/>
    	            	</span>-->
    	            	<!--<prime:messages id="messages" />-->
    					<prime:growl id="messages" showDetail="true" autoUpdate="true"/>
                	</p>
                	
                	<h:form id="projectTableForm">
    	            	<prime:dataTable id="projectTable" var="project" value="#{projectModel.projects}" editable="true">
    	            		<prime:column headerText="#{bundles.messages.project_id}">
    	            			<h:outputText value="#{project.getId}" converter="javax.faces.Long"/>
    	            		</prime:column>
    	            		<prime:column headerText="#{bundles.messages.project_name}">
    							<prime:cellEditor>  
    		            			<f:facet name="output">
    			            			<h:outputText value="#{project.getName}"/>
    			            		</f:facet>
    			            		<f:facet name="input">
    			            			<prime:inputText id="projectName" value="#{project.name}" />
    			            		</f:facet>
    			            	</prime:cellEditor>
    	            		</prime:column>
    	            		<prime:column headerText="#{bundles.messages.project_start}">
    							<prime:cellEditor>  
    		            			<f:facet name="output">
    			            			<h:outputText value="#{project.getStart}">
    			            				<f:convertDateTime pattern="dd.MM.yyyy"/>
    			            			</h:outputText>
    			            		</f:facet>
    			            		<f:facet name="input">
    			            			<prime:calendar id="startDateInput" value="#{project.start}" navigator="true" pattern="dd.MM.yyyy"/>
    			            		</f:facet>
    			            	</prime:cellEditor>
    	            		</prime:column>
    	            		<prime:column headerText="ROLES (TXTTODO)">
    	            			<!--<h:outputText value="#{project.rolesAsString}" />-->
    							<prime:cellEditor>  
    		            			<f:facet name="output">
    			            			<h:outputText value="#{project.rolesAsString}" />
    			            		</f:facet>
    			            		<f:facet name="input">
    				                    <prime:selectManyMenu id="roleNameSelector" value="#{project.roles}">
    				                    	<f:selectItems value="#{projectRoleModel.projectRoles}" var="role"
    				                    			itemLabel="#{role.name}" itemValue="#{role}">
    				                    		
    				                    	</f:selectItems>
    				                    	<!--<f:converter converterId="myDebugEntityConverter"/>-->
    				                    	<s:objectConverter/>
    				                    </prime:selectManyMenu>
    			            		</f:facet>
    			            	</prime:cellEditor>
    	            		</prime:column>
    	
    						<prime:column id="option" headerText="Options">										
    							<prime:rowEditor>
    							</prime:rowEditor>											  
    							<h:outputText value="Edit" />
    
    							<br />
    							<pretty:link mappingId="projectsAssignRoles">ROLES</pretty:link>
    							
    						</prime:column>
    	            	
    	            	</prime:dataTable>
    	            	
    	            	
    	            </h:form>
    
    
                	
                	
                	<!-- onclick="createDialog.show()" type="button" -->
                	<!-- Push Buttons don't need no form, see PrimeFaces docs -->
    				<!--<prime:commandButton id="showCreateDialog" type="button" onclick="createDialog.show()" value="#{bundles.messages.project_newProject}"/>-->
    				<h:form id="projectCreationButton">
    					<prime:commandButton 
    						value="#{bundles.messages.project_newProject}"
    						actionListener="#{projectController.startCreation()}"
    						update=":createProject"
    						oncomplete="createDialog.show()"
    					/>
    				</h:form>
    				
                
                	<prime:dialog header="#{bundles.messages.project_newProject}" widgetVar="createDialog" resizable="false" modal="true">
    		            <h:form id="createProject">
    		            	<h:panelGrid id="grid" columns="2">
    		                    <h:outputLabel value="#{bundles.messages.project_name}" for="projectName"/>
    		                    <prime:inputText id="projectName" value="#{projectController.newProject.name}" />
    		                        			<!--binding="#{projectHome.projectNameInput}" immediate="true"/>-->
    		                        	
    		                    
    		                    <h:outputLabel value="#{bundles.messages.project_description}" for="projectDescription"/>
    		                    <prime:inputTextarea id="projectDescription" value="#{projectController.newProject.description}" immediate="true"/>
    							
    		                    <h:outputLabel value="#{bundles.messages.project_start}" for="startDate"/>
    							<prime:calendar id="startDate" value="#{projectController.newProject.start}" navigator="true" pattern="dd.MM.yyyy"/>
    						</h:panelGrid>
                            <prime:commandButton id="createProjectButton" update=":projectTableForm:projectTable" oncomplete="createDialog.hide()"
                            		value="#{bundles.messages.project_createProject}" action="#{projectController.completeCreation()}"/>
                            <prime:commandButton id="cancel" type="button" value="#{bundles.messages.general_cancel}" onclick="createDialog.hide()"/>
    		       		</h:form>
    		       	</prime:dialog>
                	
                </h:panelGroup>
                
                
                
    
            </div>
        </ui:define>
    
        <ui:define name="sidebar">
                   
            <h:panelGroup rendered="#{identity.loggedIn}">
    			<pretty:link mappingId="projectsMainPage">#{bundles.messages.projects}</pretty:link><br/>
    			<pretty:link mappingId="projectsParticipations">#{bundles.messages.project_participations}</pretty:link><br/>
    			<pretty:link mappingId="projectsRoles">#{bundles.messages.project_roles}</pretty:link><br/>
            </h:panelGroup>
    
        </ui:define>
    
    </ui:composition>

***The Project entity bean (minus boring getters/setters)***:

    @Entity
    @Table(name = "project")
    @NamedQueries({
    	@NamedQuery(name = "Project.findById", query = "SELECT p FROM Project p WHERE p.id = :id"), 
        @NamedQuery(name = "Project.getAll", query = "SELECT p FROM Project p ORDER BY p.name ASC"),
        @NamedQuery(name = "Project.getNotStandardProjects", query = "SELECT p FROM Project p WHERE p.type <> :standard")
    })
    public class Project implements Serializable, Comparable<Project>, Identifiable<Long> {
    
    	@Transient
    	private static final long serialVersionUID = 1L;
    	
    	@Id
    	@NotNull
    	@GeneratedValue
    	private Long id;
    	
    	@NotNull
    	// NotBlank also ignores whitespaces as far as i can tell
    	@NotBlank
    	private String name;
    	
    	@NotNull
    	@Temporal(TemporalType.DATE)
    	private Date start;
    	
    	@Temporal(TemporalType.DATE)
    	// WORKAROUND: end is a keyword in postgresql and isn't properly escaped by hibernate
    	@Column(name="\"end\"")
    	private Date end;
    	
    	// TEXT might be postgresql-specific
    	@Lob
    	//@Column(columnDefinition="TEXT")
    	private String description;
    	
    	@OneToMany ( cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "project" )
    	@IndexColumn(name="id")
    	private List<ProjectParticipation> projectParticipation = new ArrayList<ProjectParticipation>();
    	
    	public enum ProjectType{
    		STANDARD,INTERNAL;
    	}
    	
    	@NotNull
    	private ProjectType type;
    	
    	@ManyToMany (cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    	@IndexColumn(name="id")
    	//@Fetch(value = FetchMode.SUBSELECT)
    	private List<ProjectRole> roles;
    	
    	
    	//Test against LazyInitializationException
    	@Transient
    	@Inject
    	private ProjectRoleModel projectRoleModel;
    	
    
    
    	public Project() {
    		super();
    		
    		// Default to ProjectType.STANDARD
    		this.type = ProjectType.STANDARD;
    	}
    	
    	
    	public Project(String name, Date start) {
    		this();
    		this.name = name;
    		this.start = start;
    	}
    
    
    	@Override
    	public int compareTo(Project project) {
    		
    		if ((this.start == null) && (project.start != null)) {
    			return -1;
    		} else if ((this.start != null) && (project.start == null)) {
    			return 1;
    		} else if ((this.start == null) && (project.start == null)) {
    			return 0;
    		}
    		
    		return this.start.compareTo(project.start);
    	}
    
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + ((name == null) ? 0 : name.hashCode());
    		result = prime * result + ((start == null) ? 0 : start.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;
    		Project other = (Project) obj;
    		if (name == null) {
    			if (other.name != null)
    				return false;
    		} else if (!name.equals(other.name))
    			return false;
    		if (start == null) {
    			if (other.start != null)
    				return false;
    		} else if (!start.equals(other.start))
    			return false;
    		return true;
    	}
    
    
    	@Override
    	public Long getId() {
    		return id;
    	}
    
    
    	public List<ProjectParticipation> getProjectParticipation() {
    		return projectParticipation;
    	}
    
    
    	public void setProjectParticipation(List<ProjectParticipation> projectParticipation) {
    		this.projectParticipation = projectParticipation;
    	}
    
    
    	public List<ProjectRole> getRoles() {
    		System.out.println("###### PROJECT.GETROLES ###### (for project: " + name + ")");
    		//TODO: Testy !
    		if (this.roles == null) this.roles = projectRoleModel.getProjectRoles();
    		if (this.roles == null)
    			System.out.println("###### PROJECT.GETROLES ###### WARNING: roles still null after projectRoleModel.getProjectRoles()");
    		else {
    			roles.size();
    			for(ProjectRole role : roles)
    				System.out.println("role insider: " + role.getName());
    		}
    		return roles;
    	}
    
    
    	public void setRoles(List<ProjectRole> roles) {
    		System.out.println("###### PROJECT.SETROLES ###### (for project: " + name + ")");
    		roles.size();
    		// test start
    		// trying post 8 here: https://community.jboss.org/thread/180555
    		// TODO result: didn't work
    		//if (this.roles == null) this.roles = new ArrayList<ProjectRole>();
    		if (this.roles == null) this.roles = projectRoleModel.getProjectRoles();
    		this.roles.clear();
    		this.roles.addAll(roles);
    		// old simple:
    		//this.roles = roles;
    		// test end
    	}
    	
    	
    	public String getRolesAsString() {
    		System.out.println("###### PROJECT.ROLESASSTRING ###### (for project: " + name + ")");
    		if (getRoles() == null || getRoles().size() <= 0) {
    			// TODO: this was null once but got changed to test if it caused the StringIndexOutOfBounds
    			return "";
    		}
    		StringBuilder sb = new StringBuilder();
    		Iterator<ProjectRole> iter = getRoles().iterator();
    		sb.append(iter.next().getName());
    		while (iter.hasNext()) {
    			sb.append(", " + iter.next().getName());
    		}
    		return sb.toString();
    	}
    }

***The ProjectRole entity bean (minus boring getters/setters)***:

    @Entity
    @Table(name = "projectRole")
    @NamedQueries({
    	@NamedQuery(name = "ProjectRole.findById", query = "SELECT pr FROM ProjectRole pr WHERE pr.id = :id"), 
        @NamedQuery(name = "ProjectRole.getAll", query = "SELECT pr FROM ProjectRole pr")
    })
    public class ProjectRole implements Serializable, Identifiable<Long> {
    
    	@Id
    	@GeneratedValue
    	private Long id;
    	
    	@NotNull
    	// NotBlank also ignores whitespaces as far as i can tell
    	@NotBlank
    	private String name;
    	
    	@Lob
    	//@Column(columnDefinition="TEXT")
    	private String description;
    	
    	
    	// Not sure this is a good idea
    	//@ManyToMany ( cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "roles" )
    	//private List<Project> projects = new ArrayList<Project>();
    
    	
    	public ProjectRole() {
    		
    	}
    	
    	
    	public ProjectRole(String name, String description) {
    		this.name = name;
    		this.description = description;
    	}
    	
    	
    	@Override
    	public boolean equals(Object o) {
    		if (o == null) return false;
    		if (!(o instanceof ProjectRole))
    			return false;
    		ProjectRole other = (ProjectRole)o;
    		if (other.id != null && this.id != null)
    			if (other.id.equals(this.id))
    				return true;
    			else
    				return false;
    		if (other.name != null && this.name != null)
    			if (other.name.equals(this.name))
    				return true;
    			else
    				return false;
    		return false;
    	}
    
    	
    	@Override
    	public int hashCode() {
    		if (id != null) return (int)id.longValue();
    		else if (name != null) return name.hashCode();
    		else return 0;
    	}
    
    	
    	@Override
    	public Long getId() {
    		return id;
    	}
    }

***The ProjectController Stateful ConversationScoped bean***:

    @Stateful
    @ConversationScoped
    @Named("projectController")
    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public class ProjectController implements Serializable {
    
    	@Inject
    	private Logger log;
    
    	@Inject
    	private Conversation conversation;
    
    	private Project newProject;
    
    	@Inject
    	private ProjectModel projectModel;
    
    	
    	@Begin
    	public void beginConversation() {
    		
    	}
    	
    	
    	// Called when button for popup is clicked
    	public void startCreation() {
    		newProject = new Project();
    		log.info("Began project creation. Conversation: " + conversation.getId());
    	}
    
    
    	// Called when button in creation popup is clicked
    	public void completeCreation() {
    		projectModel.persist(newProject);
    		newProject = null;
    		log.info("Persisted project. Conversation: " + conversation.getId());
    	}
    
    
    	public Project getNewProject() {
    		return newProject;
    	}
    
    
    	public void setNewProject(Project newProject) {
    		this.newProject = newProject;
    	}
    
    }

***The ProjectModel bean that handles database access***:

    @Dependent
    @Named
    @Stateless
    public class ProjectModel {
    
    	@Inject
    	private EntityManager entityManager;
    	
    	
    	public void persist (Project project) {
    		entityManager.persist(project);
    	}
    	
    	
    	public List<Project> getProjects() {
    		Query query = entityManager.createNamedQuery("Project.getAll");
    			
    		return (List<Project>)query.getResultList();
    	}
    
    	
    	public Project getProjectById(final Long id) {
    		Query query = entityManager.createNamedQuery("Project.findById");
    		query.setParameter("id", id);
    			
    		return (Project)query.getSingleResult();
    	}
    	
    }

***The seam managed persistence configuration (beans.xml)***:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
            http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
        <interceptors>
        	<class>org.jboss.seam.security.SecurityInterceptor</class>
            <class>org.jboss.seam.faces.context.conversation.ConversationBoundaryInterceptor</class>
            <class>org.jboss.seam.transaction.TransactionInterceptor</class>
        </interceptors>
        
        <alternatives>
            <class>...bootstrap.ApplicationAdminInitializer</class>
        </alternatives>
    </beans>

If you want to see my awful pom.xml just ask - couldn't post it here because of the character limit.
LazyInitializationException on SelectManyMenu in PrimeFaces CellEditor (Seam3, JSF 2.1)
===

***Summary***: When editing a row in a dataTable, I encounter a LazyInitializationException for a @ManyToMany relation that is editable with a PrimeFaces SelectManyMenu. My bean is @ConversationScoped and I'm using seam managed persistence contexts (as far as I can tell).

---

***Environment***:
JBoss AS 7.1.1.Final (Hibernate Core 4.0.1.Final, Mojarra 2.1.7), PostgreSQL 8.4, Primefaces 3.2, Seam 3.1.0.Final, Richfaces 4.1.0.Final, Maven 3.0.3, Java 1.7

***Disclaimer***: I'm quite new to JavaEE programming, Seam3 and all that stuff.

***Details***:
I'm trying to create a simple jsf page that lets the user create and edit Project objects. A Project is an entity that is mainly related to two other entities: ProjectParticipation and ProjectRole. A ProjectParticipation assigns an employee to a Project (and also specifies the ProjectRoles the employee is responsible for), which is a bi-directional OneToMany relation to Project. A ProjectRole is uni-directionally bound to Project and a ManyToMany relation.

At this stage of the project I'm not at all concerned about the performance of the application (and it most probably won't be an issue in the final application). Before introducing ProjectRole, I used FetchType.EAGER for the List of ProjectParticipations referenced in Project and this worked well. But apparently JPA/Hibernate is not able to fetch two Collections eagerly, so I had to switch to lazy fetching (I really don't care about this).

I created a simple JSF page that shows all Projects in a PrimeFaces dataTable which uses the in-cell editing feature. This all worked well until I added a PrimeFaces selectManyMenu (I also tried to replace it by a standard jsf selectManyMenu) for editing the association to ProjectRoles. It displays the state from the database correctly, but once I try to submit the new (or unedited) values, I run into a LazyInitializationException (see below). My Bean is @ConversationScoped (I'm starting the conversation on page load in f:metadata with s:viewAction and verified it is active throughout the editing), I'm also using seam managed persistence as far as I can tell (it's configured as described in the tutorials). As far as I understand it that should protect me from LIEs, but it seems no matter what I try I can't get it to work - and I don't even remotely understand where and why the Exception happens.

I'm not sure if a converter could help - but at least Seam's own s:objectConverter doesn't change anything at all when placed inside the selectManyMenu.

---

***The exception***:

        17:26:09,820 INFO  [javax.enterprise.resource.webcontainer.jsf.context] (http--127.0.0.1-8080-2) org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed
    	at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:393) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:385) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:378) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.AbstractPersistentCollection.write(AbstractPersistentCollection.java:208) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at org.hibernate.collection.internal.PersistentList.add(PersistentList.java:163) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
    	at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValuesForModel(MenuRenderer.java:382) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValue(MenuRenderer.java:129) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:315) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at org.primefaces.component.selectmanymenu.SelectManyMenuRenderer.getConvertedValue(SelectManyMenuRenderer.java:33) [primefaces-3.2.jar:]
    	at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIInput.validate(UIInput.java:960) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIInput.executeValidate(UIInput.java:1233) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIInput.processValidators(UIInput.java:698) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1612) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIData.visitRows(UIData.java:2138) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIData.visitTree(UIData.java:1437) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIForm.visitTree(UIForm.java:371) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
    	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    	at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:126) [prettyfaces-jsf2-3.3.2.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:840) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:622) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:560) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:488) [jbossweb-7.0.13.Final.jar:]
    	at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118) [prettyfaces-jsf2-3.3.2.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
    	at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
    	at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
    	at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_03-icedtea]

***The jsf page (shortened)***:

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
                    xmlns:ui="http://java.sun.com/jsf/facelets"
                    xmlns:f="http://java.sun.com/jsf/core"
                    xmlns:h="http://java.sun.com/jsf/html"
                    xmlns:pretty="http://ocpsoft.com/prettyfaces"
    				xmlns:prime="http://primefaces.org/ui" 
                    xmlns:s="http://jboss.org/seam/faces"
                    template="/WEB-INF/layout/template.xhtml">
    
    	<f:metadata>
    		<s:viewAction action="#{projectController.beginConversation()}"/>
    		<!--<s:viewAction action="#{projectHome.wire}"/>-->
    		<!-- next line is quite probably useless -->
    		<!--<s:viewAction action="#{projectRoleHome.wire}"/>-->
    	</f:metadata>
    
        <ui:define name="content">
            <div class="section">
    
                <h1>#{bundles.messages.projects}</h1>
    
                <p>#{bundles.messages.projects_intro}</p>
    
               
                <h:panelGroup rendered="#{identity.loggedIn}">
                	<p>
    		            <!--<span class="errors">
    	               		<h:messages errorClass="error" styleClass="messages" id="messages" globalOnly="true"/>
    	            	</span>-->
    	            	<!--<prime:messages id="messages" />-->
    					<prime:growl id="messages" showDetail="true" autoUpdate="true"/>
                	</p>
                	
                	<h:form id="projectTableForm">
    	            	<prime:dataTable id="projectTable" var="project" value="#{projectModel.projects}" editable="true">
    	            		<prime:column headerText="#{bundles.messages.project_id}">
    	            			<h:outputText value="#{project.getId}" converter="javax.faces.Long"/>
    	            		</prime:column>
    	            		<prime:column headerText="#{bundles.messages.project_name}">
    							<prime:cellEditor>  
    		            			<f:facet name="output">
    			            			<h:outputText value="#{project.getName}"/>
    			            		</f:facet>
    			            		<f:facet name="input">
    			            			<prime:inputText id="projectName" value="#{project.name}" />
    			            		</f:facet>
    			            	</prime:cellEditor>
    	            		</prime:column>
    	            		<prime:column headerText="#{bundles.messages.project_start}">
    							<prime:cellEditor>  
    		            			<f:facet name="output">
    			            			<h:outputText value="#{project.getStart}">
    			            				<f:convertDateTime pattern="dd.MM.yyyy"/>
    			            			</h:outputText>
    			            		</f:facet>
    			            		<f:facet name="input">
    			            			<prime:calendar id="startDateInput" value="#{project.start}" navigator="true" pattern="dd.MM.yyyy"/>
    			            		</f:facet>
    			            	</prime:cellEditor>
    	            		</prime:column>
    	            		<prime:column headerText="ROLES (TXTTODO)">
    	            			<!--<h:outputText value="#{project.rolesAsString}" />-->
    							<prime:cellEditor>  
    		            			<f:facet name="output">
    			            			<h:outputText value="#{project.rolesAsString}" />
    			            		</f:facet>
    			            		<f:facet name="input">
    				                    <prime:selectManyMenu id="roleNameSelector" value="#{project.roles}">
    				                    	<f:selectItems value="#{projectRoleModel.projectRoles}" var="role"
    				                    			itemLabel="#{role.name}" itemValue="#{role}">
    				                    		
    				                    	</f:selectItems>
    				                    	<!--<f:converter converterId="myDebugEntityConverter"/>-->
    				                    	<s:objectConverter/>
    				                    </prime:selectManyMenu>
    			            		</f:facet>
    			            	</prime:cellEditor>
    	            		</prime:column>
    	
    						<prime:column id="option" headerText="Options">										
    							<prime:rowEditor>
    							</prime:rowEditor>											  
    							<h:outputText value="Edit" />
    
    							<br />
    							<pretty:link mappingId="projectsAssignRoles">ROLES</pretty:link>
    							
    						</prime:column>
    	            	
    	            	</prime:dataTable>
    	            	
    	            	
    	            </h:form>
    
    
                	
                	
                	<!-- onclick="createDialog.show()" type="button" -->
                	<!-- Push Buttons don't need no form, see PrimeFaces docs -->
    				<!--<prime:commandButton id="showCreateDialog" type="button" onclick="createDialog.show()" value="#{bundles.messages.project_newProject}"/>-->
    				<h:form id="projectCreationButton">
    					<prime:commandButton 
    						value="#{bundles.messages.project_newProject}"
    						actionListener="#{projectController.startCreation()}"
    						update=":createProject"
    						oncomplete="createDialog.show()"
    					/>
    				</h:form>
    				
                
                	<prime:dialog header="#{bundles.messages.project_newProject}" widgetVar="createDialog" resizable="false" modal="true">
    		            <h:form id="createProject">
    		            	<h:panelGrid id="grid" columns="2">
    		                    <h:outputLabel value="#{bundles.messages.project_name}" for="projectName"/>
    		                    <prime:inputText id="projectName" value="#{projectController.newProject.name}" />
    		                        			<!--binding="#{projectHome.projectNameInput}" immediate="true"/>-->
    		                        	
    		                    
    		                    <h:outputLabel value="#{bundles.messages.project_description}" for="projectDescription"/>
    		                    <prime:inputTextarea id="projectDescription" value="#{projectController.newProject.description}" immediate="true"/>
    							
    		                    <h:outputLabel value="#{bundles.messages.project_start}" for="startDate"/>
    							<prime:calendar id="startDate" value="#{projectController.newProject.start}" navigator="true" pattern="dd.MM.yyyy"/>
    						</h:panelGrid>
                            <prime:commandButton id="createProjectButton" update=":projectTableForm:projectTable" oncomplete="createDialog.hide()"
                            		value="#{bundles.messages.project_createProject}" action="#{projectController.completeCreation()}"/>
                            <prime:commandButton id="cancel" type="button" value="#{bundles.messages.general_cancel}" onclick="createDialog.hide()"/>
    		       		</h:form>
    		       	</prime:dialog>
                	
                </h:panelGroup>
                
                
                
    
            </div>
        </ui:define>
    
        <ui:define name="sidebar">
                   
            <h:panelGroup rendered="#{identity.loggedIn}">
    			<pretty:link mappingId="projectsMainPage">#{bundles.messages.projects}</pretty:link><br/>
    			<pretty:link mappingId="projectsParticipations">#{bundles.messages.project_participations}</pretty:link><br/>
    			<pretty:link mappingId="projectsRoles">#{bundles.messages.project_roles}</pretty:link><br/>
            </h:panelGroup>
    
        </ui:define>
    
    </ui:composition>

***The Project entity bean (minus boring getters/setters)***:

    @Entity
    @Table(name = "project")
    @NamedQueries({
    	@NamedQuery(name = "Project.findById", query = "SELECT p FROM Project p WHERE p.id = :id"), 
        @NamedQuery(name = "Project.getAll", query = "SELECT p FROM Project p ORDER BY p.name ASC"),
        @NamedQuery(name = "Project.getNotStandardProjects", query = "SELECT p FROM Project p WHERE p.type <> :standard")
    })
    public class Project implements Serializable, Comparable<Project>, Identifiable<Long> {
    
    	@Transient
    	private static final long serialVersionUID = 1L;
    	
    	@Id
    	@NotNull
    	@GeneratedValue
    	private Long id;
    	
    	@NotNull
    	// NotBlank also ignores whitespaces as far as i can tell
    	@NotBlank
    	private String name;
    	
    	@NotNull
    	@Temporal(TemporalType.DATE)
    	private Date start;
    	
    	@Temporal(TemporalType.DATE)
    	// WORKAROUND: end is a keyword in postgresql and isn't properly escaped by hibernate
    	@Column(name="\"end\"")
    	private Date end;
    	
    	// TEXT might be postgresql-specific
    	@Lob
    	//@Column(columnDefinition="TEXT")
    	private String description;
    	
    	@OneToMany ( cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "project" )
    	@IndexColumn(name="id")
    	private List<ProjectParticipation> projectParticipation = new ArrayList<ProjectParticipation>();
    	
    	public enum ProjectType{
    		STANDARD,INTERNAL;
    	}
    	
    	@NotNull
    	private ProjectType type;
    	
    	@ManyToMany (cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    	@IndexColumn(name="id")
    	//@Fetch(value = FetchMode.SUBSELECT)
    	private List<ProjectRole> roles;
    	
    	
    	//Test against LazyInitializationException
    	@Transient
    	@Inject
    	private ProjectRoleModel projectRoleModel;
    	
    
    
    	public Project() {
    		super();
    		
    		// Default to ProjectType.STANDARD
    		this.type = ProjectType.STANDARD;
    	}
    	
    	
    	public Project(String name, Date start) {
    		this();
    		this.name = name;
    		this.start = start;
    	}
    
    
    	@Override
    	public int compareTo(Project project) {
    		
    		if ((this.start == null) && (project.start != null)) {
    			return -1;
    		} else if ((this.start != null) && (project.start == null)) {
    			return 1;
    		} else if ((this.start == null) && (project.start == null)) {
    			return 0;
    		}
    		
    		return this.start.compareTo(project.start);
    	}
    
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + ((name == null) ? 0 : name.hashCode());
    		result = prime * result + ((start == null) ? 0 : start.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;
    		Project other = (Project) obj;
    		if (name == null) {
    			if (other.name != null)
    				return false;
    		} else if (!name.equals(other.name))
    			return false;
    		if (start == null) {
    			if (other.start != null)
    				return false;
    		} else if (!start.equals(other.start))
    			return false;
    		return true;
    	}
    
    
    	@Override
    	public Long getId() {
    		return id;
    	}
    
    
    	public List<ProjectParticipation> getProjectParticipation() {
    		return projectParticipation;
    	}
    
    
    	public void setProjectParticipation(List<ProjectParticipation> projectParticipation) {
    		this.projectParticipation = projectParticipation;
    	}
    
    
    	public List<ProjectRole> getRoles() {
    		System.out.println("###### PROJECT.GETROLES ###### (for project: " + name + ")");
    		//TODO: Testy !
    		if (this.roles == null) this.roles = projectRoleModel.getProjectRoles();
    		if (this.roles == null)
    			System.out.println("###### PROJECT.GETROLES ###### WARNING: roles still null after projectRoleModel.getProjectRoles()");
    		else {
    			roles.size();
    			for(ProjectRole role : roles)
    				System.out.println("role insider: " + role.getName());
    		}
    		return roles;
    	}
    
    
    	public void setRoles(List<ProjectRole> roles) {
    		System.out.println("###### PROJECT.SETROLES ###### (for project: " + name + ")");
    		roles.size();
    		// test start
    		// trying post 8 here: https://community.jboss.org/thread/180555
    		// TODO result: didn't work
    		//if (this.roles == null) this.roles = new ArrayList<ProjectRole>();
    		if (this.roles == null) this.roles = projectRoleModel.getProjectRoles();
    		this.roles.clear();
    		this.roles.addAll(roles);
    		// old simple:
    		//this.roles = roles;
    		// test end
    	}
    	
    	
    	public String getRolesAsString() {
    		System.out.println("###### PROJECT.ROLESASSTRING ###### (for project: " + name + ")");
    		if (getRoles() == null || getRoles().size() <= 0) {
    			// TODO: this was null once but got changed to test if it caused the StringIndexOutOfBounds
    			return "";
    		}
    		StringBuilder sb = new StringBuilder();
    		Iterator<ProjectRole> iter = getRoles().iterator();
    		sb.append(iter.next().getName());
    		while (iter.hasNext()) {
    			sb.append(", " + iter.next().getName());
    		}
    		return sb.toString();
    	}
    }

***The ProjectRole entity bean (minus boring getters/setters)***:

    @Entity
    @Table(name = "projectRole")
    @NamedQueries({
    	@NamedQuery(name = "ProjectRole.findById", query = "SELECT pr FROM ProjectRole pr WHERE pr.id = :id"), 
        @NamedQuery(name = "ProjectRole.getAll", query = "SELECT pr FROM ProjectRole pr")
    })
    public class ProjectRole implements Serializable, Identifiable<Long> {
    
    	@Id
    	@GeneratedValue
    	private Long id;
    	
    	@NotNull
    	// NotBlank also ignores whitespaces as far as i can tell
    	@NotBlank
    	private String name;
    	
    	@Lob
    	//@Column(columnDefinition="TEXT")
    	private String description;
    	
    	
    	// Not sure this is a good idea
    	//@ManyToMany ( cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "roles" )
    	//private List<Project> projects = new ArrayList<Project>();
    
    	
    	public ProjectRole() {
    		
    	}
    	
    	
    	public ProjectRole(String name, String description) {
    		this.name = name;
    		this.description = description;
    	}
    	
    	
    	@Override
    	public boolean equals(Object o) {
    		if (o == null) return false;
    		if (!(o instanceof ProjectRole))
    			return false;
    		ProjectRole other = (ProjectRole)o;
    		if (other.id != null && this.id != null)
    			if (other.id.equals(this.id))
    				return true;
    			else
    				return false;
    		if (other.name != null && this.name != null)
    			if (other.name.equals(this.name))
    				return true;
    			else
    				return false;
    		return false;
    	}
    
    	
    	@Override
    	public int hashCode() {
    		if (id != null) return (int)id.longValue();
    		else if (name != null) return name.hashCode();
    		else return 0;
    	}
    
    	
    	@Override
    	public Long getId() {
    		return id;
    	}
    }

***The ProjectController Stateful ConversationScoped bean***:

    @Stateful
    @ConversationScoped
    @Named("projectController")
    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public class ProjectController implements Serializable {
    
    	@Inject
    	private Logger log;
    
    	@Inject
    	private Conversation conversation;
    
    	private Project newProject;
    
    	@Inject
    	private ProjectModel projectModel;
    
    	
    	@Begin
    	public void beginConversation() {
    		
    	}
    	
    	
    	// Called when button for popup is clicked
    	public void startCreation() {
    		newProject = new Project();
    		log.info("Began project creation. Conversation: " + conversation.getId());
    	}
    
    
    	// Called when button in creation popup is clicked
    	public void completeCreation() {
    		projectModel.persist(newProject);
    		newProject = null;
    		log.info("Persisted project. Conversation: " + conversation.getId());
    	}
    
    
    	public Project getNewProject() {
    		return newProject;
    	}
    
    
    	public void setNewProject(Project newProject) {
    		this.newProject = newProject;
    	}
    
    }

***The ProjectModel bean that handles database access***:

    @Dependent
    @Named
    @Stateless
    public class ProjectModel {
    
    	@Inject
    	private EntityManager entityManager;
    	
    	
    	public void persist (Project project) {
    		entityManager.persist(project);
    	}
    	
    	
    	public List<Project> getProjects() {
    		Query query = entityManager.createNamedQuery("Project.getAll");
    			
    		return (List<Project>)query.getResultList();
    	}
    
    	
    	public Project getProjectById(final Long id) {
    		Query query = entityManager.createNamedQuery("Project.findById");
    		query.setParameter("id", id);
    			
    		return (Project)query.getSingleResult();
    	}
    	
    }

***The seam managed persistence configuration (beans.xml)***:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
            http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
        <interceptors>
        	<class>org.jboss.seam.security.SecurityInterceptor</class>
            <class>org.jboss.seam.faces.context.conversation.ConversationBoundaryInterceptor</class>
            <class>org.jboss.seam.transaction.TransactionInterceptor</class>
        </interceptors>
        
        <alternatives>
            <class>...bootstrap.ApplicationAdminInitializer</class>
        </alternatives>
    </beans>

If you want to see my awful pom.xml just ask - couldn't post it here because of the character limit.