2

I have a bean that contain an attribute List<String> with @ElementCollection annotation. My problem is when I try get values contained at list, an exception returns and I don't know why. I can add values but I can't return this values.

Look at constructor class TableListView, I can't use System.out that returns exception. Look at method update() of class UnidadeEscolarForm, in this method I get the bean about your id code. Look at method bindingFields(UnidadeEscolar bean), I create a instance of TableListView slv = new TableListView(bean) and send the bean.

Using java swing, when I create a bean with elementcollection and I do bean.getlist() I can get values of collection but with vaadin I don't know how do this.

Here how I'm trying

    //my bean
    @Entity
    public class UnidadeEscolar implements Serializable{
        private static final long serialVersionUID = 1L;

        @Id @GeneratedValue
        private Long id;

        @NotNull @Size(min=5, max=50) @Column(unique=true)
        private String nome;


        @ElementCollection
        private List<String> telefones = new ArrayList<String>();

        /** add telefones **/
        public void addTelefoneUnidadeEscolar(String tfe){      
            telefones.add(tfe);
        }

        /** remove telefones */
        public void removeTelefoneUnidadeEscolar(int row){
            telefones.remove(row);
        }

        public List<String> getTelefones() {
            return telefones;
        }



    // add/show values list
    public class TableListView extends VerticalLayout implements Button.ClickListener, ItemClickListener, ValueChangeListener{  
        private static final long serialVersionUID = 1L;
        private Button add;
        private Button delete;
        private HorizontalLayout buttonLayout;
        private TelefoneField txtField;
        private Table tabela;
        private UnidadeEscolar bean;
        private Integer tableItem;
        private CheckBox add9;


        public TableListView(UnidadeEscolar bean){
            this.bean = bean;   
            System.out.println(bean.getTelefones()); //here exception 
            buildMainLayout();
        }


        private void buildMainLayout(){
            setSpacing(false);
            tabela = new Table("");
            tabela.setHeight("100px");
            tabela.setWidth("200px");
            tabela.addContainerProperty("Telefone", String.class, null);
            tabela.setSelectable(true);
            tabela.addItemClickListener(this);

            addComponent(tabela);
            addComponent(buildButtonLayout());      
        }

        private HorizontalLayout buildButtonLayout(){
            buttonLayout = new HorizontalLayout();      
            txtField = new TelefoneField();
            txtField.setAdd9(true);
            add = new Button("+");
            delete = new Button("-");
            add9 = new CheckBox("Adiciona9", true);
            //listeners
            add9.addValueChangeListener(this);
            add.addClickListener(this);
            delete.addClickListener(this);

            buttonLayout.addComponent(txtField);
            buttonLayout.addComponent(add);
            buttonLayout.addComponent(delete);
            buttonLayout.addComponent(add9);
            return buttonLayout;
        }



        @Override
        public void buttonClick(ClickEvent event) {
            //add values
            if(event.getButton() == add){           
                if(txtField.getValue().trim().isEmpty()){
                    Notification.show("Insira o número do telefone");
                }else{
                    Object addItem = tabela.addItem();
                    tabela.getItem(addItem).getItemProperty("Telefone").setValue(txtField.getValue());
                    bean.addTelefoneUnidadeEscolar(txtField.getValue());
                    txtField.setValue("");
                }           
            }

            //remove values
            if(event.getButton() == delete){            
                tabela.removeItem(tableItem);
                bean.removeTelefoneUnidadeEscolar(tableItem);
            }       
        }


        @Override
        public void itemClick(ItemClickEvent event) {
            tableItem = Integer.parseInt(event.getItemId().toString());
        }


        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean value = (Boolean) event.getProperty().getValue();
            txtField.setAdd9(value);        
        }
    }



    //forms 
    public class UnidadeEscolarForm extends CustomComponent implements Button.ClickListener{
        private static final long serialVersionUID = 1L;
        private FormLayout mainLayout;

        private Button btnSalvar, btnSair;
        private Boolean isEdit = false; //verifica se esta editando(alterando)

        //fields
            private TextField id;
            private TextUpper nome;
            private ComboBox departamento;
            private CepField cep;
            private TextUpper endereco;
            private TextUpper numero;
            private TextUpper complemento;
            private TextUpper bairro;
            private TextUpper cidade;
            private ComboBox uf;
            private CheckBox add9;
            private ComboBox telefone;
            private TextLower email;
            private ComboBox status;


        //logger
        private static Logger log = Logger.getLogger(UnidadeEscolar.class);
        //datasource
        private CustomJPAContainer<UnidadeEscolar> datasource;
        //binder
        private BeanFieldGroup<UnidadeEscolar> binder;



        public UnidadeEscolarForm(CustomJPAContainer<UnidadeEscolar> datasource){
            this.datasource = datasource;
            buildLayout();
            setCompositionRoot(mainLayout);
        }

        private FormLayout buildLayout(){
            mainLayout = new FormLayout();
            mainLayout.setMargin(true);

            return mainLayout;
        }

        /** insere novo registro de modalidade */
        public void insert(){
            bindingFields(new UnidadeEscolar());
        }

        /** altera registro existente de modalidade */
        public void update(Long id){
            try{
                UnidadeEscolar ue = datasource.getItem(id).getEntity();
                bindingFields(ue);
                isEdit = true;          
            }catch(Exception e){
                log.error("Não foi possível carregar a tela de edição: " + e.getMessage());
                Notification.show("Não foi possível carregar a tela de edição" + e.getMessage(), Type.ERROR_MESSAGE);
            }               
        }

        private void bindingFields(UnidadeEscolar bean){
            binder = new BeanFieldGroup<UnidadeEscolar>(UnidadeEscolar.class);
            binder.setItemDataSource(bean);
            Field<?> field = null;

            //combobox factory
            //combobox fieldfactory
            binder.setFieldFactory(new DefaultFieldGroupFieldFactory() {
                @Override
                public <T extends Field> T createField(Class<?> type, Class<T> fieldType) {
                    if (type.isAssignableFrom(String.class) && fieldType.isAssignableFrom(ComboBox.class)) {
                        return (T) new ComboBox();
                    }       
                    return super.createField(type, fieldType);
                }
            });

            //fields
            field = binder.buildAndBind("Nome:", "nome", TextUpper.class);
            nome = (TextUpper)field;
            nome.setMaxLength(50);
            nome.setWidth("10cm");
            mainLayout.addComponent(nome);

            field = binder.buildAndBind("Departamento:", "departamento", ComboBox.class);
            departamento = (ComboBox)field;
            departamento.select(Departamento.values());
            mainLayout.addComponent(departamento);

            field = binder.buildAndBind("Cep:", "cep", CepField.class);
            cep = (CepField)field;
            mainLayout.addComponent(cep);

            field = binder.buildAndBind("Endereço:", "endereco", TextUpper.class);
            endereco = (TextUpper)field;
            endereco.setMaxLength(50);
            endereco.setWidth("10cm");
            mainLayout.addComponent(endereco);

            field = binder.buildAndBind("Numero:", "numero", TextUpper.class);
            numero = (TextUpper)field;
            numero.setMaxLength(8);
            numero.setWidth("2cm");
            mainLayout.addComponent(numero);

            field = binder.buildAndBind("Complemento:", "complemento", TextUpper.class);
            complemento = (TextUpper)field;
            complemento.setWidth("5cm");
            complemento.setMaxLength(50);
            mainLayout.addComponent(complemento);

            field = binder.buildAndBind("Bairro:", "bairro", TextUpper.class);
            bairro = (TextUpper)field;
            bairro.setWidth("5cm");
            bairro.setMaxLength(50);
            mainLayout.addComponent(bairro);

            field = binder.buildAndBind("Cidade:", "cidade", TextUpper.class);
            cidade = (TextUpper)field;
            cidade.setWidth("5cm");
            cidade.setMaxLength(50);
            mainLayout.addComponent(cidade);

            field = binder.buildAndBind("UF:", "uf", ComboBox.class);
            uf = (ComboBox)field;
            uf.setWidth("2cm");
            mainLayout.addComponent(uf);


            field = binder.buildAndBind("Email:", "email", TextLower.class);
            email = (TextLower)field;
            email.setWidth("10cm");
            email.setMaxLength(250);
            mainLayout.addComponent(email);

            //lista de telefones
            TableListView slv = new TableListView(bean);        
            mainLayout.addComponent(slv);

            //botoes
            HorizontalLayout hLayout = new HorizontalLayout();
            hLayout.setSpacing(true);
            btnSalvar = new Button("Salvar");
            btnSalvar.setWidth("100px");
            btnSalvar.setIcon(new ThemeResource(Assets.BTN_SALVAR));
            btnSalvar.setDescription("Salvar/Alterar");
            btnSalvar.addClickListener(this);
            hLayout.addComponent(btnSalvar);

            btnSair = new Button("Sair");
            btnSair.setWidth("100px");
            btnSair.setIcon(new ThemeResource(Assets.BTN_SAIR));
            btnSair.setDescription("Sair");
            btnSair.setClickShortcut(KeyCode.ESCAPE);
            btnSair.addClickListener(this);
            hLayout.addComponent(btnSair);  
            mainLayout.addComponent(hLayout);

            nome.focus();
            nome.selectAll();
        }

        /** insere ou altera uma modalidade */
        private void insertUpdate(){
            try {               
                binder.commit();
                try {                   
                    datasource.addEntity(binder.getItemDataSource().getBean());
                    if(isEdit){//verifica se esta editando
                        Window w = (Window)getParent();
                        w.close();
                    }else{
                        clearFields();
                    }
                } catch(PersistenceException e) {
                    Notification.show("Dados inválidos!\n"+e.getMessage(), Type.ERROR_MESSAGE);
                    return;
                }
            } catch (CommitException e) {
                Notification.show("Informações não inseridas \n", 
                          "Verifique todos os campos necessários", 
                          Type.ERROR_MESSAGE);
            }
        }

        private void clearFields(){
            nome.setValue("");
            departamento.select(Departamento.ESTADUAL);
            cep.setValue("");
            endereco.setValue("");
            numero.setValue("");
            complemento.setValue("");
            bairro.setValue("");
            cidade.setValue("");
            uf.select(EstadosDoBrasil.AC);
            email.setValue("");

            nome.focus();
        }

        @Override
        public void buttonClick(ClickEvent event) {
            if(event.getButton() == btnSalvar){
                insertUpdate();
            }else if(event.getButton() == btnSair){
                Window w = (Window)getParent();
                w.close();
            }
        }
    }


//here exception
ago 07, 2014 3:42:12 PM com.vaadin.server.DefaultErrorHandler doDefault
GRAVE: 
com.vaadin.server.ServerRpcManager$RpcInvocationException: Unable to invoke method click in com.vaadin.shared.ui.button.ButtonServerRpc
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:170)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)
    at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:207)
    at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
    at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:168)
    ... 30 more
Caused by: com.vaadin.event.ListenerMethod$MethodException: Invocation of method buttonClick in br.com.webapp.views.UnidadeEscolarView2 failed.
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:528)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
    at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:969)
    at com.vaadin.ui.Button.fireClick(Button.java:368)
    at com.vaadin.ui.Button$1.click(Button.java:57)
    ... 35 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:430)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:121)
    at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:500)
    at java.lang.String.valueOf(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at org.apache.tomcat.util.log.SystemLogHandler.println(SystemLogHandler.java:267)
    at br.com.webapp.utils.TableListView.<init>(TableListView.java:31)
    at br.com.webapp.views.UnidadeEscolarForm.bindingFields(UnidadeEscolarForm.java:174)
    at br.com.webapp.views.UnidadeEscolarForm.update(UnidadeEscolarForm.java:90)
    at br.com.webapp.views.UnidadeEscolarView2.buttonClick(UnidadeEscolarView2.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
    ... 40 more
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118

2 Answers2

2

The error occurs because you're trying to read the elements of a list on a lazy way, without having a session open attached to the UnidadeEscolar object.

See this answer for a more elaborated explanation:

LazyInitializationException when using ElementCollection in Play framework

Community
  • 1
  • 1
squallsv
  • 482
  • 2
  • 11
  • wow dude, now works I marked `@ElementCollection(fetch=FetchType.EAGER)` and now works :D !!! Thanks a lot (y) – FernandoPaiva Aug 08 '14 at 00:23
  • I strongly recommend that you read more about this. `FetchType.EAGER` solves your problem, but it's not a very good practice in most cases. Here are some material to read about this subject: http://www.javacodegeeks.com/2012/08/hibernate-lazyeager-loading-example.html http://java.dzone.com/articles/jpa-lazy-loading – squallsv Aug 08 '14 at 18:21
0

You are missing a closing bracket (}) somewhere. Probably at the end of your bean...


Consider the line where you are having a problem:

System.out.println(bean.getTelefones()); //here exception 

You are attempting to print the result of bean.getTelefones(). That function returns a List<String>. You can't just print out a List of something.

To print the entire list:

String todosTelefones = "";
for (String s : bean.getTelefones())
    todosTelefones += s;
System.out.println(todosTelefones );

To print out a single String element in the List:

System.out.println(bean.getTelefones().get(index));
Rainbolt
  • 3,542
  • 1
  • 20
  • 44
  • @FernandoPaiva Is it the *same* exception on the *same* line? You can't print out a List, so I have fixed at least one of your problems. – Rainbolt Aug 07 '14 at 19:13
  • I tried `for(String x : bean.getTelefones()){ System.out.println(x); }` and same exception is return – FernandoPaiva Aug 07 '14 at 19:29