Java Spring connection with wamp. I do not insert the record

1

I am learning the Java Spring Framework and following a tutorial I made some classes with the repsective attributes that coincided with the ones I have mounted in the database. And what I intend is to the data in the Database of my WAMP Server

I have 4 main packages:

  • beans
  • dao
  • service
  • main

Beans Package

    public class Camiseta {

        private int id;
        private int numero;
        private Marca marca;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getNumero() {
            return numero;
        }

        public void setNumero(int numero) {
            this.numero = numero;
        }

        public Marca getMarca() {
            return marca;
        }

        public void setMarca(Marca marca) {
            this.marca = marca;
        }

    }






    public class Equipo {

        private int id;
        private String nombre;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getNombre() {
            return nombre;
        }

        public void setNombre(String nombre) {
            this.nombre = nombre;
        }

    }




public class Jugador {

    private int id;
    private String nombre;
    private Equipo equipo;
    private Camiseta camiseta;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public Equipo getEquipo() {
        return equipo;
    }

    public void setEquipo(Equipo equipo) {
        this.equipo = equipo;
    }

    public Camiseta getCamiseta() {
        return camiseta;
    }

    public void setCamiseta(Camiseta camiseta) {
        this.camiseta = camiseta;
    }

}



public class Marca {

    private int id;
    private String nombre;



    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

}

Dao package

import com.mitocode.beans.Marca;

public interface DAOMarca {

    public void registrar(Marca marca) throws Exception;
}



import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mitocode.beans.Marca;


@Repository //estereotipo de una determinada capa
public  class DAOMarcaImpl implements DAOMarca {

    @Autowired
    private DataSource dataSource;


    public void registrar(Marca marca) throws Exception {
        // TODO Auto-generated method stub

        String sql = "INSERT INTO marca(marca_id, marca_nombre) VALUES (?,?)";
        Connection con = null;
        try {
            con =  dataSource.getConnection();
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1, marca.getId());
            ps.setString(2, marca.getNombre());
            ps.executeUpdate();
            ps.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        finally {
            if (con != null) {
                con.close();
            }
        }
    }

}

Service package

import com.mitocode.beans.Marca;

public interface ServiceMarca {
    public void registrar(Marca marca) throws Exception;

}


import org.springframework.stereotype.Service;

import com.mitocode.beans.Marca;
import com.mitocode.dao.DAOMarca;

@Service
public class ServiceMarcaImpl implements ServiceMarca {

private DAOMarca daoMarca;

    public void registrar(Marca marca) throws Exception {
        // TODO Auto-generated method stub
        try {
            daoMarca.registrar(marca);

        } catch (Exception e) {
            // TODO: handle exception
        }
        finally {

        }
    }

}

Package main

Marca marca = new Marca();
marca.setId(666);
marca.setNombre("Mi marca");


ApplicationContext appContext = new ClassPathXmlApplicationContext("com/mitocode/xml/beans.xml");

ServiceMarca sm = (ServiceMarca) appContext.getBean("serviceMarcaImpl");


try {
    sm.registrar(marca);
} catch (Exception e) {
    // TODO: handle exception
    System.out.println("Error insercion: "+e);
}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:component-scan base-package="com.mitocode"></context:component-scan>


    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/db_spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
    </bean>

</beans>

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mitocode</groupId>
    <artifactId>springbd</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springbd</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>

    </dependencies>
</project>

My problem arises when inserting into the database that it does not and I do not know why. Also add that I do not get an error at any time. Both in the XML structures and when calling the method that inserts the mark in the closed main in try catch.

I have found new information about my error. In class ServiceMarca.java gives me an exception java.lang.NullPointerException

    
asked by josanangel 20.08.2018 в 13:16
source

2 answers

1

I am writing to you in response because it will not let me add comment. Have you seen that the application.properties file has the datasource properly configured? I think that the connection to the database is not doing well for that. The application.properties file is within resources.

Edit: I think something fails to connect to the database. Try connecting as follows:

DataSource ds = (DataSource)ApplicationContextProvider.getApplicationContext().getBean("dataSource");
Connection c = ds.getConnection();

Edit: Sorry; You have to declare an ApplicationContext in the following way, in the Dao Package:

@Autowired
private ApplicationContext appContext;

Then make the connection in the following way:

DataSource ds = (DataSource)appContext.getBean("dataSource");
Connection c = ds.getConnection();

The dao package would look like this:

import com.mitocode.beans.Marca;

public interface DAOMarca {

    public void registrar(Marca marca) throws Exception;
}



import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mitocode.beans.Marca;


@Repository //estereotipo de una determinada capa
public  class DAOMarcaImpl implements DAOMarca {

    @Autowired
    private ApplicationContext appContext;

private DataSource ds;


    public void registrar(Marca marca) throws Exception {
        // TODO Auto-generated method stub

        String sql = "INSERT INTO marca(marca_id, marca_nombre) VALUES (?,?)";
        Connection con = null;
        try {
ds=(DataSource)appContext.getBean("dataSource");
            con =  ds.getConnection();
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1, marca.getId());
            ps.setString(2, marca.getNombre());
            ps.executeUpdate();
            ps.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        finally {
            if (con != null) {
                con.close();
            }
        }
    }

}

I add new information discovered:

I get Error 'Service Marca': java.lang.NullPointerException in class ServiceMarca.java

I think I already know what it is. It was something simpler than all that.

Modify the ServiceMarcaImpl class such that:

@Service
public class ServiceMarcaImpl implements ServiceMarca {

@Autowired
private DAOMarcaImpl daoMarca;

    public void registrar(Marca marca) throws Exception {
        // TODO Auto-generated method stub
        try {
            daoMarca.registrar(marca);

        } catch (Exception e) {
            // TODO: handle exception
        }
        finally {

        }
    }

}

It happens because you are creating an object of an interface instead of its implementation.

    
answered by 21.08.2018 / 22:07
source
0

Do not you get anything, if you do SOUT before making the insert either? Maybe you're not looking at the right log record.

    
answered by 21.08.2018 в 18:54