我有一个包含带List<String>
注释的属性@ElementCollection
的bean。
我的问题是,当我尝试获取列表中包含的值时,异常返回,我不知道为什么。我可以添加值,但我无法返回此值。
查看构造函数类TableListView,我不能使用返回异常的System.out。
查看类UnidadeEscolarForm的方法update()
,在这个方法中我得到关于你的id代码的bean。
查看方法bindingFields(UnidadeEscolar bean)
,创建TableListView slv = new TableListView(bean)
的实例并发送bean。
使用java swing,当我使用elementcollection创建一个bean并且我执行bean.getlist()时,我可以获得集合的值,但是使用vaadin我不知道怎么做。
我在这里尝试
//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
答案 0 :(得分:2)
发生错误是因为您试图以懒惰的方式读取列表的元素,而没有将会话打开附加到UnidadeEscolar
对象。
请参阅此答案以获得更详细的解释:
LazyInitializationException when using ElementCollection in Play framework
答案 1 :(得分:0)
你错过了一个结束括号(}
)。可能在你的bean结尾......
考虑您遇到问题的行:
System.out.println(bean.getTelefones()); //here exception
您正在尝试打印bean.getTelefones()
的结果。该函数返回List<String>
。你不能打印出某个东西的清单。
要打印整个列表:
String todosTelefones = "";
for (String s : bean.getTelefones())
todosTelefones += s;
System.out.println(todosTelefones );
打印List中的单个String元素:
System.out.println(bean.getTelefones().get(index));