Olá, estou lendo um livro (Programação java para web) muito bom...
mas, estou com um problema num fonte do livro
ele não grava no banco de dados Postgres...
fontes:
MAIN/*
* Código-fonte do livro "Programando Java para Web"
* Autores: Décio Heinzelmann Luckow <[email removido]>
* Alexandre Altair de Melo <[email removido]>
*
* ISBN: 978-85-7522-238-6
* http://www.novatec.com.br/livros/javaparaweb
* Editora Novatec, 2010 - todos os direitos reservados
*
* LICENÇA: Este arquivo-fonte está sujeito a Atribuição 2.5 Brasil, da licença Creative Commons,
* que encontra-se disponível no seguinte endereço URI: http://creativecommons.org/licenses/by/2.5/br/
* Se você não recebeu uma cópia desta licença, e não conseguiu obtê-la pela internet, por favor,
* envie uma notificação aos seus autores para que eles possam enviá-la para você imediatamente.
*
*
* Source-code of "Programando Java para Web" book
* Authors: Décio Heinzelmann Luckow <[email removido]>
* Alexandre Altair de Melo <[email removido]>
*
* ISBN: 978-85-7522-238-6
* http://www.novatec.com.br/livros/javaparaweb
* Editora Novatec, 2010 - all rights reserved
*
* LICENSE: This source file is subject to Attribution version 2.5 Brazil of the Creative Commons
* license that is available through the following URI: http://creativecommons.org/licenses/by/2.5/br/
* If you did not receive a copy of this license and are unable to obtain it through the web, please
* send a note to the authors so they can mail you a copy immediately.
*
*/
package com.livro.capitulo3.locadora;
import java.sql.Date;
import java.sql.Time;
import java.util.List;
import com.livro.capitulo3.categoria.Categoria;
import com.livro.capitulo3.categoria.CategoriaDAO;
import com.livro.capitulo3.cliente.Cliente;
import com.livro.capitulo3.cliente.ClienteDAO;
import com.livro.capitulo3.endereco.Endereco;
import com.livro.capitulo3.endereco.EnderecoDAO;
import com.livro.capitulo3.filme.Filme;
import com.livro.capitulo3.filme.FilmeDAO;
import com.livro.capitulo3.locacao.Locacao;
import com.livro.capitulo3.locacao.LocacaoDAO;
import com.livro.capitulo3.midia.Midia;
import com.livro.capitulo3.midia.MidiaDAO;
import com.livro.capitulo3.util.HibernateUtil;
/*
* Classe para testes do sistema da locadora.
*/
public class Locadora {
public static void main(String[] args) {
HibernateUtil.getSessionFactory().openSession();
//Locadora locadora = new Locadora();
//locadora.cadastraCategorias();
//locadora.cadastraFilmes();
//locadora.cadastraMidias();
EnderecoDAO enderecoDAO = new EnderecoDAO();
Endereco endereco = new Endereco();
Cliente cliente = new Cliente();
ClienteDAO clienteDAO = new ClienteDAO();
cliente.setCelular("([telefone removido]");
cliente.setEmail("[email removido]");
cliente.setNome("Fulano Solaris");
cliente.setTelefone("([telefone removido]");
cliente.setEndereco(endereco);
endereco.setBairro("Centro");
endereco.setCep("89000-000");
endereco.setCidade("Joinville");
endereco.setComplemento("casa");
endereco.setNumero(new Integer(1));
endereco.setRua("Av. Principal");
endereco.setUf("SC");
endereco.setCliente(cliente);
clienteDAO.salvar(cliente);
enderecoDAO.salvar(endereco);
/*LocacaoDAO locacaoDAO = new LocacaoDAO();
Locacao locacao = new Locacao();
locacao.setDataDevolucao(new Date(System.currentTimeMillis()));
locacao.setDataEmprestimo(new Date(System.currentTimeMillis()));
locacao.setObservacao("Devolução final de semana");
locacao.setHoraEmprestimo(new Time(System.currentTimeMillis()));
locacao.setCliente(cliente);
MidiaDAO midiaDAO = new MidiaDAO();
Midia midia = (Midia) midiaDAO.buscaMidia(new Integer(1));
locacao.setMidia(midia);
locacaoDAO.salvar(locacao);
System.out.println("Cadastros gerados com sucesso!");*/
}
public void cadastraCategorias() {
//Criando as categorias dos filmes
String categorias[] = {"Aventura", "Ação", "Comédia"};
Categoria categoria = null;
CategoriaDAO categoriaDAO = new CategoriaDAO();
for (int i = 0; i < 3; i++) {
categoria = new Categoria();
categoria.setDescricao(categorias[i]);
categoriaDAO.salvar(categoria);
}
}
public void cadastraFilmes() {
CategoriaDAO categoriaDAO = new CategoriaDAO();
String[] filmesDescricao = {"Senhor dos Anéis", "Transformers", "Ghostbusters"};
//Aqui subtraímos o ano de lançamento do filme de 1900, para gravarmos o ano correto no banco.
Date[] filmesAnoProducao = {new Date(2001-1900, 11, 19), new Date(2007-1900, 6, 20), new Date(1985-1900, 1, 1)};
FilmeDAO filmeDAO = new FilmeDAO();
Filme filme = null;
for (int i = 0; i < 3; i++) {
filme = new Filme();
filme.setDescricao(filmesDescricao[i]);
filme.setAno(filmesAnoProducao[i]);
filme.setCategoria(categoriaDAO.buscaCategoria(i + 1));
filmeDAO.salvar(filme);
}
}
public void cadastraMidias() {
Midia midia = null;
Filme filme = null;
MidiaDAO midiaDAO = new MidiaDAO();
FilmeDAO filmeDAO = new FilmeDAO();
List<Filme> resultado = filmeDAO.listar();
for (int i = 0; i < 3; i++) {
midia = new Midia();
filme = (Filme) resultado.get(i);
midia.setFilme(filme);
midia.setInutilizada("N");
midiaDAO.salvar(midia);
}
}
}
/*
* Código-fonte do livro "Programando Java para Web"
* Autores: Décio Heinzelmann Luckow <[email removido]>
* Alexandre Altair de Melo <[email removido]>
*
* ISBN: 978-85-7522-238-6
* http://www.novatec.com.br/livros/javaparaweb
* Editora Novatec, 2010 - todos os direitos reservados
*
* LICENÇA: Este arquivo-fonte está sujeito a Atribuição 2.5 Brasil, da licença Creative Commons,
* que encontra-se disponível no seguinte endereço URI: http://creativecommons.org/licenses/by/2.5/br/
* Se você não recebeu uma cópia desta licença, e não conseguiu obtê-la pela internet, por favor,
* envie uma notificação aos seus autores para que eles possam enviá-la para você imediatamente.
*
*
* Source-code of "Programando Java para Web" book
* Authors: Décio Heinzelmann Luckow <[email removido]>
* Alexandre Altair de Melo <[email removido]>
*
* ISBN: 978-85-7522-238-6
* http://www.novatec.com.br/livros/javaparaweb
* Editora Novatec, 2010 - all rights reserved
*
* LICENSE: This source file is subject to Attribution version 2.5 Brazil of the Creative Commons
* license that is available through the following URI: http://creativecommons.org/licenses/by/2.5/br/
* If you did not receive a copy of this license and are unable to obtain it through the web, please
* send a note to the authors so they can mail you a copy immediately.
*
*/
package com.livro.capitulo3.cliente;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.livro.capitulo3.endereco.Endereco;
import com.livro.capitulo3.locacao.Locacao;
@Entity
@Table(name = "cliente")
public class Cliente implements Serializable {
private static final long serialVersionUID = -1707591652638708533L;
@Id
@GeneratedValue
@Column(name = "cod_cliente")
private Integer cliente;
@OneToOne
@PrimaryKeyJoinColumn(name = "cod_cliente")
private Endereco endereco;
@OneToMany(mappedBy="cliente")
private List<Locacao> locacoes;
private String nome;
private String telefone;
private String celular;
private String email;
public Integer getCliente() {
return cliente;
}
public void setCliente(Integer cliente) {
this.cliente = cliente;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public List<Locacao> getLocacoes() {
return locacoes;
}
public void setLocacoes(List<Locacao> locacoes) {
this.locacoes = locacoes;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((celular == null) ? 0 : celular.hashCode());
result = prime * result + ((cliente == null) ? 0 : cliente.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((endereco == null) ? 0 : endereco.hashCode());
result = prime * result + ((locacoes == null) ? 0 : locacoes.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((telefone == null) ? 0 : telefone.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;
final Cliente other = (Cliente) obj;
if (celular == null) {
if (other.celular != null)
return false;
} else if (!celular.equals(other.celular))
return false;
if (cliente == null) {
if (other.cliente != null)
return false;
} else if (!cliente.equals(other.cliente))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (endereco == null) {
if (other.endereco != null)
return false;
} else if (!endereco.equals(other.endereco))
return false;
if (locacoes == null) {
if (other.locacoes != null)
return false;
} else if (!locacoes.equals(other.locacoes))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (telefone == null) {
if (other.telefone != null)
return false;
} else if (!telefone.equals(other.telefone))
return false;
return true;
}
}
/*
* Código-fonte do livro "Programando Java para Web"
* Autores: Décio Heinzelmann Luckow <[email removido]>
* Alexandre Altair de Melo <[email removido]>
*
* ISBN: 978-85-7522-238-6
* http://www.novatec.com.br/livros/javaparaweb
* Editora Novatec, 2010 - todos os direitos reservados
*
* LICENÇA: Este arquivo-fonte está sujeito a Atribuição 2.5 Brasil, da licença Creative Commons,
* que encontra-se disponível no seguinte endereço URI: http://creativecommons.org/licenses/by/2.5/br/
* Se você não recebeu uma cópia desta licença, e não conseguiu obtê-la pela internet, por favor,
* envie uma notificação aos seus autores para que eles possam enviá-la para você imediatamente.
*
*
* Source-code of "Programando Java para Web" book
* Authors: Décio Heinzelmann Luckow <[email removido]>
* Alexandre Altair de Melo <[email removido]>
*
* ISBN: 978-85-7522-238-6
* http://www.novatec.com.br/livros/javaparaweb
* Editora Novatec, 2010 - all rights reserved
*
* LICENSE: This source file is subject to Attribution version 2.5 Brazil of the Creative Commons
* license that is available through the following URI: http://creativecommons.org/licenses/by/2.5/br/
* If you did not receive a copy of this license and are unable to obtain it through the web, please
* send a note to the authors so they can mail you a copy immediately.
*
*/
package com.livro.capitulo3.endereco;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Parameter;
import com.livro.capitulo3.cliente.Cliente;
@Entity
@Table(name = "endereco")
public class Endereco implements Serializable {
private static final long serialVersionUID = 1280791770249284855L;
@Id
@GeneratedValue(generator = "fk_endereco_cod_cliente")
@org.hibernate.annotations.GenericGenerator(name = "fk_endereco_cod_cliente", strategy = "foreign", parameters = @Parameter(name = "property", value = "cliente"))
@Column(name = "cod_cliente")
private Integer endereco;
@OneToOne(mappedBy="endereco")
private Cliente cliente;
private String rua;
private Integer numero;
private String bairro;
private String cidade;
@Column(name = "estado")
private String uf;
private String cep;
private String complemento;
public Integer getEndereco() {
return endereco;
}
public void setEndereco(Integer endereco) {
this.endereco = endereco;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public Integer getNumero() {
return numero;
}
public void setNumero(Integer numero) {
this.numero = numero;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
}
create table categoria
(
cod_categoria serial not null,
descricao varchar(50) null,
primary key (cod_categoria)
);
create table filme
(
cod_filme serial not null,
cod_categoria integer null,
descricao varchar(50),
ano date null,
primary key (cod_filme),
constraint fk_filme_cod_categoria foreign key (cod_categoria) references categoria (cod_categoria) on delete no action on update cascade
);
create table cliente
(
cod_cliente serial not null,
nome varchar(100) null,
telefone varchar(50) null,
celular varchar(50) null,
email varchar(255) null,
primary key (cod_cliente)
);
create table midia
(
cod_midia serial not null,
cod_filme integer not null,
inutilizada char(1) null,
primary key (cod_midia),
constraint fk_midia_cod_filme foreign key (cod_filme) references filme (cod_filme) on delete no action on update cascade
);
create table locacao
(
cod_locacao serial not null,
cod_cliente integer not null,
cod_midia integer not null,
data_emprestimo date null,
hora_emprestimo time null,
data_devolucao date null,
obs text null,
primary key (cod_locacao, cod_cliente, cod_midia),
constraint fk_locacao_cod_cliente foreign key (cod_cliente) references cliente (cod_cliente) on delete no action on update cascade,
constraint fk_locacao_cod_midia foreign key (cod_midia) references midia (cod_midia) on delete no action on update cascade
);
create table endereco
(
cod_cliente integer not null,
rua varchar(100) null,
numero integer null,
bairro varchar(100) null,
cidade varchar(100) null,
estado char(2) null,
cep varchar(10) null,
complemento text null,
primary key (cod_cliente),
constraint fk_endereco_cod_cliente foreign key (cod_cliente) references cliente (cod_cliente) on delete no action on update cascade
);
6 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.5.2-Final
66 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.5.2-Final
70 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
78 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
89 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
368 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
382 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: hibernate.cfg.xml
382 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: hibernate.cfg.xml
559 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
567 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
683 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.livro.capitulo3.categoria.Categoria
761 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.livro.capitulo3.categoria.Categoria on table categoria
840 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.livro.capitulo3.filme.Filme
842 [main] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: filmePorChavePrimaria => select f from Filme f where f.filme = :filme
842 [main] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: filmePorDescricao => select f from Filme f where f.descricao like :descricao
842 [main] INFO org.hibernate.cfg.annotations.QueryBinder - Binding Named query: filmePorCategoria => select f from Filme f join f.categoria c where c.categoria = :categoria
843 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.livro.capitulo3.filme.Filme on table filme
862 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.livro.capitulo3.midia.Midia
863 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.livro.capitulo3.midia.Midia on table midia
866 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.livro.capitulo3.cliente.Cliente
866 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.livro.capitulo3.cliente.Cliente on table cliente
924 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.livro.capitulo3.endereco.Endereco
924 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.livro.capitulo3.endereco.Endereco on table endereco
940 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.livro.capitulo3.locacao.Locacao
941 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.livro.capitulo3.locacao.Locacao on table locacao
1052 [main] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.livro.capitulo3.cliente.Cliente.locacoes -> locacao
1056 [main] INFO org.hibernate.cfg.AnnotationConfiguration - Hibernate Validator not found: ignoring
1068 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
1068 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
1068 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
1102 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/locadora
1102 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=postgres, password=****}
1276 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: PostgreSQL, version: 9.1.4
1276 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 9.2 JDBC4 (build 1002)
1315 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect
1329 [main] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
1331 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
1333 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
1333 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
1333 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
1333 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
1333 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
1334 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
1334 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
1334 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
1335 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
1335 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: enabled
1335 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
1335 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
1335 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
1337 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
1337 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
1337 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
1337 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
1337 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
1337 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
1337 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
1337 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
1343 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
1343 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: enabled
1343 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
1344 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
1344 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
1344 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
1396 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
1736 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
Hibernate:
select
nextval ('hibernate_sequence')
2098 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42P01
2098 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: relação "hibernate_sequence" não existe
Posição: 17
Não foi possível inserir o cliente. Erro: could not get next sequence value
Hibernate:
select
nextval ('hibernate_sequence')
2102 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 25P02
2102 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: transação atual foi interrompida, comandos ignorados até o fim do bloco de transação
Não foi possível inserir o endereço. Erro: could not get next sequence value
ajuda?