Bom dia Colegas!
Estou estudando o Spring para implementá-lo no meu projeto.
Adquiri o livro do Yuri Marx P. Gomes: Java na Web com JSF - Spring, Hibernate e Netbeans 6.
Baixei todas as ferraentas indicadas pelo autor e estou implementando o exemplo citado no livro.
Quando vou realizar o teste, está ocorrendo um erro no qual já fiz várias intervenções e não consegui resolver.
A mensagem de erro é a seguinte: "Connections could not be acquired from the underlying database!".
Utilizo o MySql. O servidor está iniciado, banco e tabelas criados como pede o livro.
Vendo algumas mensagens sobre este erro, algumas pessoas informam que é necessáro "subir" o banco de dados.
Porém, utilizando o netbeans pela parte de serviços a conexão é estabelecida normalmente. Também acesso o banco atráves do MySql sem nenhum problema.
O que pode estar ocorrendo então?
Agradeço a ajuda de todos e envio abaixo o script do exemplo:
applicationContext:
[url]
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
[/url]
persistence:
[url]
[/url]
jdbc.properties:
# To change this template, choose Tools | Templates
# and open the template in the editor.
# Configurações para MySQL
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/agenda
jdbc.username=root
jdbc.password=root
jdbc.dialect=org.hibernate.dialect.MySQLDialect
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package facade;
import dao.UsuarioDao;
import dominio.Usuario;
import java.util.List;
/**
*
* @author Ronaldo
*/
public class UsuarioFacade {
private UsuarioDao usuarioDao;
/** Creates a new instance of UsuarioFacade*/
public UsuarioFacade(){
}
public Usuario gravar(Usuario usuario){
return usuarioDao.gravar(usuario);
}
public void excluir(Usuario usuario){
usuarioDao.excluir(usuario);
}
public Usuario carregar(Integer id){
return usuarioDao.carregar(id);
}
public List obterTodos() {
return usuarioDao.obterTodos();
}
public List ObterPorNome(String nome){
return usuarioDao.obterPorNome(nome);
}
public Usuario obterPorLoginSenha(String login, String senha){
return usuarioDao.obterPorLoginSenha(login, senha);
}
public UsuarioDao getUsuarioDao(){
return usuarioDao;
}
public void setUsuarioDao(UsuarioDao usuarioDao){
this.usuarioDao = usuarioDao;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package facade;
import dao.UsuarioDao;
import dominio.Usuario;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
/**
*
* @author Ronaldo
*/
public class UsuarioFacadeTest {
public UsuarioFacadeTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of gravar method, of class UsuarioFacade.
*/
@Test
public void testGravar() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Usuario usuario = new Usuario();
usuario.setLogin("guest");
usuario.setNome("guest");
usuario.setSenha("guest");
System.out.println("gravar usuario");
UsuarioFacade instance = (UsuarioFacade)context.getBean("usuarioFacade");
// Usuario expResult = instance.gravar(usuario);
Usuario result = instance.gravar(usuario);
try {
assertNotNull(result.getIdUsuario() );
} catch (AssertionError e) {
fail("Falhou a gravação de usuário");
}
}
/**
* Test of excluir method, of class UsuarioFacade.
*/
@Test
public void testExcluir() {
System.out.println("excluir");
Usuario usuario = null;
UsuarioFacade instance = new UsuarioFacade();
instance.excluir(usuario);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of carregar method, of class UsuarioFacade.
*/
@Test
public void testCarregar() {
System.out.println("carregar");
Integer id = null;
UsuarioFacade instance = new UsuarioFacade();
Usuario expResult = null;
Usuario result = instance.carregar(id);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of obterTodos method, of class UsuarioFacade.
*/
@Test
public void testObterTodos() {
System.out.println("obterTodos");
UsuarioFacade instance = new UsuarioFacade();
List expResult = null;
List result = instance.obterTodos();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of ObterPorNome method, of class UsuarioFacade.
*/
@Test
public void testObterPorNome() {
System.out.println("ObterPorNome");
String nome = "";
UsuarioFacade instance = new UsuarioFacade();
List expResult = null;
List result = instance.ObterPorNome(nome);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of obterPorLoginSenha method, of class UsuarioFacade.
*/
@Test
public void testObterPorLoginSenha() {
System.out.println("obterPorLoginSenha");
String login = "";
String senha = "";
UsuarioFacade instance = new UsuarioFacade();
Usuario expResult = null;
Usuario result = instance.obterPorLoginSenha(login, senha);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getUsuarioDao method, of class UsuarioFacade.
*/
@Test
public void testGetUsuarioDao() {
System.out.println("getUsuarioDao");
UsuarioFacade instance = new UsuarioFacade();
UsuarioDao expResult = null;
UsuarioDao result = instance.getUsuarioDao();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setUsuarioDao method, of class UsuarioFacade.
*/
@Test
public void testSetUsuarioDao() {
System.out.println("setUsuarioDao");
UsuarioDao usuarioDao = null;
UsuarioFacade instance = new UsuarioFacade();
instance.setUsuarioDao(usuarioDao);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import dominio.Usuario;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Ronaldo
*/
@Repository
@Transactional
public class UsuarioDao {
@PersistenceContext
private EntityManager em;
/** Creates a new instance of UsuarioDado */
public UsuarioDao() {
}
public Usuario gravar(Usuario usuario) throws DataAccessException{
return em.merge(usuario);
}
public void excluir(Usuario usuario) throws DataAccessException {
em.remove(carregar(usuario.getIdUsuario()));
}
public Usuario carregar(Integer id) throws DataAccessException {
return em.find(Usuario.class, id);
}
public List obterTodos() throws DataAccessException{
return em.createQuery("SELECT u FROM Usuario u").getResultList();
}
public List obterPorNome(String nome) throws DataAccessException{
Query qry = em.createQuery("SELECT u FROM Usuario u WHERE u.nome LIKE :nome");
qry.setParameter("nome", "%" + nome + "%");
return qry.getResultList();
}
public List obterPorLogin(String login) throws DataAccessException{
Query qry = em.createQuery("SELECT u FROM Usuario u WHERE u.login LIKE :login");
qry.setParameter("login", "%" + login + "%");
return qry.getResultList();
}
public Usuario obterPorLoginSenha(String login, String senha) throws DataAccessException{
Query qry = em.createQuery("SELECT u FROM Usuario u WHERE u.login LIKE:login AND u.senha = :senha");
qry.setParameter("login", login);
qry.setParameter("senha", senha);
List resultados = qry.getResultList();
if(resultados.size() > 0){
return (Usuario) resultados.get(0);
} else {
return null;
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dominio;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author Ronaldo
*/
@Entity
@Table(name = "usuario")
@NamedQueries({@NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u")})
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Basic(optional = false)
@Column(name = "idUsuario")
private Integer idUsuario;
@Basic(optional = false)
@Column(name = "nome")
private String nome;
@Basic(optional = false)
@Column(name = "login")
private String login;
@Basic(optional = false)
@Column(name = "senha")
private String senha;
@OneToMany(mappedBy = "idUsuario")
private Collection<Contato> contatoCollection;
public Usuario() {
}
public Usuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public Usuario(Integer idUsuario, String nome, String login, String senha) {
this.idUsuario = idUsuario;
this.nome = nome;
this.login = login;
this.senha = senha;
}
public Integer getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public Collection<Contato> getContatoCollection() {
return contatoCollection;
}
public void setContatoCollection(Collection<Contato> contatoCollection) {
this.contatoCollection = contatoCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idUsuario != null ? idUsuario.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.idUsuario == null && other.idUsuario != null) || (this.idUsuario != null && !this.idUsuario.equals(other.idUsuario))) {
return false;
}
return true;
}
@Override
public String toString() {
return "dominio.Usuario[idUsuario=" + idUsuario + "]";
}
}