Warning: Trying to access array offset on value of type bool in /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php on line 16

Warning: Trying to access array offset on value of type bool in /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php on line 16

Warning: Trying to access array offset on value of type bool in /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php on line 16

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758

Warning: Cannot modify header information - headers already sent by (output started at /home/feltexco/public_html/felix/wp-content/plugins/google-maps-ready/modules/options/models/options.php:16) in /home/feltexco/public_html/felix/wp-includes/rest-api/class-wp-rest-server.php on line 1758
{"id":1478,"date":"2014-10-17T08:28:44","date_gmt":"2014-10-17T11:28:44","guid":{"rendered":"http:\/\/www.feltex.com.br\/felix\/?p=1478"},"modified":"2014-12-29T18:22:21","modified_gmt":"2014-12-29T20:22:21","slug":"fazer-batch-update-java","status":"publish","type":"post","link":"https:\/\/www.feltex.com.br\/felix\/fazer-batch-update-java\/","title":{"rendered":"Batch update: Como fazer atualiza\u00e7\u00e3o em lote em Java:"},"content":{"rendered":"

Como fazer atualiza\u00e7\u00e3o em lote em Java: batch update<\/H1><\/p>\n

Ol\u00e1 Amigos, hoje iremos mostrar como podemos fazer atualiza\u00e7\u00e3o em Lote no Java o chamado batch update. Para isso precisaremos criar uma massa de teste com 10000 registros. Em seguida ser\u00e1 feita uma inser\u00e7\u00e3o via JDBC utilizando Insert normalmente e outra vez utilizando a abordagem batch update. Veja a seguir os resultados que tivemos batch update X Insert simples.
\n\"Batch<\/p>\n

<\/p>\n

1. Criando a tabela do banco de dados<\/H2>
\n Segue o script para a cria\u00e7\u00e3o da tabela.<\/p>\n
\r\n CREATE TABLE tbaluno (\r\n matricula INT NOT NULL ,\r\n nome VARCHAR(45) NULL ,\r\n telefone VARCHAR(45) NULL ,\r\n email VARCHAR(45) NULL ,\r\n datacadastro DATETIME NULL );\r\n<\/pre>\n

Aten\u00e7\u00e3o: n\u00e3o foi criada a chave prim\u00e1ria para evitar conflito na gera\u00e7\u00e3o das chaves pelo programa!<\/strong><\/p>\n

2. Constru\u00e7\u00e3o da classe de modelo<\/H2><\/p>\n

Inicialmente devemos criar a classe Aluno conforme c\u00f3digo abaixo.
\nEla servir\u00e1 como modelo de neg\u00f3cio para atualizarmos a tabela no banco de dados.<\/p>\n

\r\npackage br.com.feltex.jdbc;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.Date;\r\n\r\npublic class Aluno implements Serializable {\r\n\r\n\tprivate static final long serialVersionUID = -309513637403441918L;\r\n\r\n\tprivate Long matricula;\r\n\r\n\tprivate String nome;\r\n\r\n\tprivate String telefone;\r\n\r\n\tprivate String email;\r\n\r\n\tprivate String endereco;\r\n\r\n\tprivate Date dataCadastro;\r\n\r\n\tpublic Aluno() {\r\n\t}\r\n\r\n\tpublic Aluno(Long matricula) {\r\n\t\tsuper();\r\n\t\tthis.matricula = matricula;\r\n\t}\r\n\r\n\tpublic Aluno(Long matricula, String nome) {\r\n\t\tsuper();\r\n\t\tthis.matricula = matricula;\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic Date getDataCadastro() {\r\n\t\treturn dataCadastro;\r\n\t}\r\n\r\n\tpublic String getEmail() {\r\n\t\treturn email;\r\n\t}\r\n\r\n\tpublic String getEndereco() {\r\n\t\treturn endereco;\r\n\t}\r\n\r\n\tpublic Long getMatricula() {\r\n\t\treturn matricula;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n\r\n\tpublic String getTelefone() {\r\n\t\treturn telefone;\r\n\t}\r\n\r\n\tpublic void setDataCadastro(Date dataCadastro) {\r\n\t\tthis.dataCadastro = dataCadastro;\r\n\t}\r\n\r\n\tpublic void setEmail(String email) {\r\n\t\tthis.email = email;\r\n\t}\r\n\r\n\tpublic void setEndereco(String endereco) {\r\n\t\tthis.endereco = endereco;\r\n\t}\r\n\r\n\tpublic void setMatricula(Long matricula) {\r\n\t\tthis.matricula = matricula;\r\n\t}\r\n\r\n\tpublic void setNome(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic void setTelefone(String telefone) {\r\n\t\tthis.telefone = telefone;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"Aluno [matricula=\" + matricula + \", nome=\" + nome\r\n\t\t\t\t+ \", telefone=\" + telefone + \", email=\" + email\r\n\t\t\t\t+ \", dataCadastro=\" + dataCadastro + \"]\";\r\n\t}\r\n\r\n}\r\n<\/pre>\n

3. A classe que realiza as opera\u00e7\u00f5es <\/H2><\/p>\n

A seguir teremos a classe principal que executar\u00e1 as a\u00e7\u00f5es no banco de dados e far\u00e1 a compara\u00e7\u00e3o entre os tempos gastos entre as opera\u00e7\u00f5es Uma a uma e tipo de atualiza\u00e7\u00e3o via lote.<\/p>\n

Temos o m\u00e9todo “gerarMassa” que criar\u00e1 uma cole\u00e7\u00e3o de alunos que ser\u00e1 inserido no Banco de dados. O m\u00e9todo “executarBatch” faz as inser\u00e7\u00f5es dos dados em blocos. Temos tamb\u00e9m o “executarUnitario” que faz as inser\u00e7\u00f5es item por item. H\u00e1 tamb\u00e9m o m\u00e9todo “getConexao” que recupera um conex\u00e3o com o banco de Dados. Por \u00faltimo, mas n\u00e3o menos importante, h\u00e1 o m\u00e9todo “main” que inicia a aplica\u00e7\u00e3o.<\/p>\n

\r\n\r\npackage br.com.feltex.jdbc.avancado;\r\n\r\nimport java.sql.Connection;\r\nimport java.sql.DriverManager;\r\nimport java.sql.PreparedStatement;\r\nimport java.util.ArrayList;\r\nimport java.util.Date;\r\nimport java.util.List;\r\n\r\nimport br.com.feltex.jdbc.Aluno;\r\npublic class Transacao {\r\n\tpublic static void gerarMassa(){\r\n\t\tfor (int i = 0; i < 10000; i++) {\r\n\t\t\tAluno aluno = new Aluno();\r\n\t\t\taluno.setMatricula(Long.valueOf(i));\r\n\t\t\taluno.setNome(\"Jose\" + i);\r\n\t\t\taluno.setTelefone(\"22352-\" + i);\r\n\t\t\taluno.setEmail(\"Jose\" + i + \"@feltex.com.br\");\r\n\t\t\taluno.setEndereco(\"RUA a Numero: \" + i);\r\n\t\t\taluno.setDataCadastro(new Date());\r\n\t\t\tlistaAlunos.add(aluno);\r\n\t\t}\r\n\t}\r\n\r\n\tstatic List listaAlunos = new ArrayList<>();\r\n\tpublic static void executarBatch() {\t\t \r\n\t\tLong inicio = System.currentTimeMillis();\r\n\t\tLong fim = 0L;\r\n\t\tConnection conexao = null;\r\n\t\ttry {\r\n\r\n\t\t\tconexao = getConexao();\r\n\t\t\tconexao.setAutoCommit(false);\r\n\r\n\t\t\tPreparedStatement pstm = conexao\r\n\t\t\t\t\t.prepareStatement(\"Insert into\ttbaluno (matricula, nome,\" + \" telefone, email, datacadastro) values\t(?,?,?,?,?)\");\r\n\tint contador = 0;\r\n\tfor (Aluno aluno : listaAlunos) {\r\n\t contador++;\r\n\tpstm.setLong(1, aluno.getMatricula());\r\n\tpstm.setString(2, aluno.getNome());\r\n\tpstm.setString(3, aluno.getTelefone());\r\n\tpstm.setString(4, aluno.getEmail());\r\n\tpstm.setDate(5, new java.sql.Date(aluno.getDataCadastro()\r\n\t\t\t\t\t.getTime()));\r\n\tpstm.addBatch();\r\n\t}\r\n\r\n\tif ((contador % 100) == 0) {\r\n\t\t\tpstm.executeBatch();\r\n\t}\r\n\r\n\tconexao.commit();\r\n\tpstm.close();\r\n\tconexao.close();\r\n\tfim = System.currentTimeMillis();\r\n\r\n\t} catch (Exception e) {\r\n\t try {\r\n\tconexao.rollback();\r\n\t} catch (Exception e2) {\r\n\t e.printStackTrace();\r\n\t}\r\n\t e.printStackTrace();\r\n\t}\r\n\tSystem.out.println(\"executarBatch Tempo total[ms]: \"\r\n\t\t+ (fim - inicio));\r\n\t}\r\n\r\n\tpublic static void executarUnitario() {\r\n\t\tLong inicio = System.currentTimeMillis();\r\n\t\tLong fim = 0L;\r\n\t\tConnection conexao = null;\r\n\t\ttry {\r\n\r\n\t\t\tconexao = getConexao();\r\n\t\t\tPreparedStatement pstm = conexao\r\n\t\t\t\t\t.prepareStatement(\"Insert into\ttbaluno (matricula, nome,\"\r\n\t\t\t\t\t\t\t+ \" telefone, email, datacadastro) values\t(?,?,?,?,?)\");\r\n\r\n\t\t\tfor (Aluno aluno : listaAlunos) {\r\n\t\t\t\tpstm.setLong(1, aluno.getMatricula());\r\n\t\t\t\tpstm.setString(2, aluno.getNome());\r\n\t\t\t\tpstm.setString(3, aluno.getTelefone());\r\n\t\t\t\tpstm.setString(4, aluno.getEmail());\r\n\t\t\t\tpstm.setDate(5, new java.sql.Date(aluno.getDataCadastro()\r\n\t\t\t\t\t\t.getTime()));\r\n\t\t\t\tpstm.execute();\r\n\t\t\t}\r\n\t\t\tpstm.close();\r\n\t\t\tconexao.close();\r\n\t\t\tfim = System.currentTimeMillis();\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\r\n\t\tSystem.out.println(\"executarUnitario Tempo total [ms]: \"\r\n\t\t\t\t+ (fim - inicio));\r\n\t}\r\n\r\n\t\r\n\t\/**\r\n\t * \r\n\t * @return\r\n\t *\/\r\n\t\r\n\tpublic static Connection getConexao() {\r\n\t\t\/\/TODO Remover este c\u00f3digo desta classe\r\n\t\tConnection conexao = null;\r\n\t\tString usuario = \"root\";\r\n\t\tString senha = \"root\";\r\n\t\tString nomeBancoDados = \"bdacademicnet\";\r\n\r\n\t\ttry {\r\n\t\t\tconexao = DriverManager.getConnection(\r\n\t\t\t\t\t\"jdbc:mysql:\/\/localhost:3306\/\" + nomeBancoDados, usuario,\r\n\t\t\t\t\tsenha);\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn conexao;\r\n\t}\r\n\r\n\tpublic static void main(String[] args) {\r\n\r\n\t\tgerarMassa();\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\texecutarUnitario();\r\n\t\t\texecutarBatch();\t\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t}\r\n}\r\n<\/pre>\n

A sa\u00edda deve ser parecida com a imagem abaixo:<\/p>\n

\r\n<\/pre>\n

4. Conclus\u00e3o<\/H2><\/p>\n

A execu\u00e7\u00e3o desde exemplo nos mostra qual a vantagem de utilizamos de utilizar a grava\u00e7\u00e3o em lotes quando temos grandes volumes de dados. Observe que o resultados s\u00e3o bem diferentes. Quando utilizamos a grava\u00e7\u00e3o batch update com um volume consider\u00e1vel de dados temos um ganho de desempenho.
\n Isto \u00e9 apenas o in\u00edcio. Aproveite para ler os links relacionados abaixo e buscar mais informa\u00e7\u00f5es sobre o assunto.
\nEnt\u00e3o \u00e9 isso. Por hoje \u00e9 s\u00f3 e vida que segue.<\/p>\n

Links relacionados<\/H2><\/p>\n