Solucionado (ver solução)
Solucionado
(ver solução)
6
respostas

Estou criando um projeto com servlet e o banco não está sendo criado

Bom, estou criando um crud de clientes utilizando o servlet mais não está sendo criado o banco o que pode está acontecendo. Vou deixar to codigo abaixo:

Codigo:

@Entity
@Table(name = "clients")
public class Client {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private Login login;
    
    public Client(String nome, Login login) {
        this.nome = nome;
        this.login = login;
    }

    public Long getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }

    public Login getLogin() {
        return login;
    }
}
public class Login {
    
    private String email;
    private String senha;
    
    public Login(String email, String senha) {
        super();
        this.email = email;
        this.senha = senha;
    }

    public String getEmail() {
        return email;
    }
    
    public String getSenha() {
        return senha;
    }
    
}

public class ClientRepository {

    public void cadastrarCliente(Client client) throws SQLException {

        EntityManager manager = JPAUtil.getEntityManager();
        EntityTransaction transaction = manager.getTransaction();

        try {
            transaction.begin();
            manager.persist(client);
            transaction.commit();
        } catch (Exception e) {
            
            if (transaction.isActive()) {
                transaction.rollback();
            }
            
            throw new SQLException(e);
        } finally {
            JPAUtil.closeEntityManager();
        }
    }
}
public class ClientService {

    private ClientRepository repository = new ClientRepository();

    public void cadatrarCliente(Client client) throws SQLException {

        String nome = client.getNome();
        String email = client.getLogin().getEmail();
        String senha = client.getLogin().getSenha();

        String senhaHash = BCrypt.hashpw(senha, BCrypt.gensalt());
        
        Login login = new Login(email, senhaHash);
        
        Client clientCadastrado = new Client(nome, login);
        
        repository.cadastrarCliente(clientCadastrado);
        
    }
}
public class CadastrarClientesBean implements TipoAcao {
    
    private HttpServletRequest req;
    private HttpServletResponse resp;
    
    public CadastrarClientesBean(HttpServletRequest req, HttpServletResponse resp) {
        super();
        this.req = req;
        this.resp = resp;
    }

    @Override
    public void execute() throws ServletException, IOException, SQLException {
        
        String nome = this.req.getParameter("nome");
        String email = this.req.getParameter("email");
        String senha = this.req.getParameter("senha");
        
        Login login = new Login(email, senha);
        
        Client client = new Client(nome, login);
        
        ClientService service = new ClientService();
        
        service.cadatrarCliente(client);
        
    }
}
public interface TipoAcao {
    void execute() throws ServletException, IOException, SQLException ;
}
@WebServlet(urlPatterns = "/client")
public class ClienteController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String action = req.getParameter("acao");

        String fqn = "br.com.client.bean." + Character.toUpperCase(action.charAt(0)) + action.substring(1);

        try {
            Class<?> classe = Class.forName(fqn);
            Constructor<?> constructor = classe.getDeclaredConstructor(HttpServletRequest.class,
                    HttpServletResponse.class);
            TipoAcao tipoAcao = (TipoAcao) constructor.newInstance(req, resp);
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new ServletException(e);
        }

    }

}
public class JPAUtil {
    
    private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Client");

    public static EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    public static void closeEntityManager() {
        entityManagerFactory.close();
    }
}
6 respostas
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
    version="3.0">
    <persistence-unit name="Client"
        transaction-type="RESOURCE_LOCAL">
        <class>br.com.client.entities.Client</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:mysql://localhost/client?createDatabaseIfNotExist=true" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password"
                value="root" />
            <property name="hibernate.dialect"
                value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>client</groupId>
    <artifactId>client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mindrot/jbcrypt -->
        <dependency>
            <groupId>org.mindrot</groupId>
            <artifactId>jbcrypt</artifactId>
            <version>0.4</version>
        </dependency>

        <!--
        https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.1.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <release>20</release>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>
        </plugins>
    </build>
</project>

Pastas dos diretorios:

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Oi!

Na sua classe Controller, após instanciar o objeto TipoAcao, faltou chamar o método execute:

TipoAcao tipoAcao = (TipoAcao) constructor.newInstance(req, resp);
tipoAcao.execute();

Obs: o arquivo persistence.xml deve ficar dentro da pasta: Java Resources/META-INF

No caso seria nessa pasta meta-inf que o arquivo está?

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Está dando esse erro:

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Não. Essa pasta META-INF está dentro de webapp, mas você deve criar outra pasta chamada também META-INF, mas dentro de Java Resources (junto com os pacotes do projeto).

solução!

O ideal na verdade é você criar outro source folder no projeto chamado src/main/resources e criar dentro desse a pasta META-INF

Consegui, obrigado!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software