Date field not saved in Spring and Angular database

Asked

Viewed 379 times

1

I am doing a small CRUD and na when I save the data the data fields Start and dataFim do not save in the database. PS: I did the debug and the dates are going through the save method.

                            <div class="form-group col-md-4">
                              <label>* Data de início:</label>
                                <input name="inpDataInicio"  type="date" class="form-control" ng-model="promocao.dataInicial" />
                             </div> 
                               <div class="form-group col-md-4">
                                 <label>* Data de fim:</label>
                                 <input name="inpDataFim"  type="date" class="form-control"   ng-model="promocao.dataFinal"/>
                             </div> 

Controller

app.controller("promocaoController", function($scope, $http){

    $scope.promocoes = [];
    $scope.promocao={ }; // binding com o form  



carregarPromocoes = function() {

        //token=localStorage.getItem("userToken");
        //$http.defaults.headers.common.Authorization = 'Bearer ' + token;

        $http({
            method : 'GET',
            url : 'http://localhost:8080/promocoes'
        }).then(function(response) {
            $scope.promocoes = response.data;


        }, function(response) {
            console.log(response.data);
            console.log(response.status);
        });
    }; 

    $scope.salvarPromocoes=function(){
        if($scope.frmPromocao.$valid){
        $http({
            method : 'POST',
            url : 'http://localhost:8080/promocoes', data:$scope.promocao
        }).then(function(response) {
            // $scope.clientes.push(response.data);
             $("#modalSalvoSucesso").modal("show");
            carregarPromocoes();
            $scope.promocao={};


        }, function(response) {
            console.log(response.data);
            console.log(response.status);
        });


        }else{
             $("#modalCampoObrigatorio").modal("show");

        }

    };



    $scope.excluirPromocoes=function(promocao){
        bootbox.confirm({
            message: "Deseja excluir o registro permanentemente ?",
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> Cancelar'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> Sim'
                }
            },
            callback: function (result) {
                if(result == true){
                    $http({
                        method : 'DELETE',
                        url : 'http://localhost:8080/promocoes/'+promocao.id
                    }).then(function(response) {

                        pos= $scope.promocoes.indexOf(promocao);
                        $scope.promocoes.splice(pos,1);


                    }, function(response) {
                        console.log(response.data);
                        console.log(response.status);
                    });
                }
            }
        });
        }; 

        $scope.alterarPromocoes=function(pro){

            $scope.promocao=angular.copy(pro); 

        };

        $scope.cancelarAlteracaoPromocoes=function(){
            $scope.promocao={};
        };

    carregarPromocoes();

});

Java controller

@RestController
@RequestMapping
public class PromocaoController {

    @Autowired
    PromocaoService promocaoService;


    //end points


    @RequestMapping(method=RequestMethod.POST, value="/promocoes", consumes=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Promocao> cadastrarPromocao(@RequestBody Promocao promocao){
        Promocao promocaoCadastrada = promocaoService.cadastrar(promocao);
        return new ResponseEntity<Promocao>(promocaoCadastrada, HttpStatus.CREATED);
    }


    @RequestMapping(method=RequestMethod.GET, value="/promocoes", produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Collection<Promocao>> buscarTodasPromocoes(){

        Collection<Promocao> promocaoBuscadas= promocaoService.buscarTodos();
        return new ResponseEntity<>(promocaoBuscadas, HttpStatus.OK);
    } 

    @RequestMapping(method=RequestMethod.GET, value="/promocoes/{id}", produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Promocao> buscarPromocaoPorId(@PathVariable int id){

        Promocao promocao= promocaoService.buscaPorId(id);
        return new ResponseEntity<>(promocao, HttpStatus.OK);
    } 


    @RequestMapping(method=RequestMethod.DELETE, value="/promocoes/{id}")
    public ResponseEntity<Promocao> excluirPromocao(@PathVariable int id){
        Promocao promocaoEncontrada = promocaoService.buscaPorId(id);
        if(promocaoEncontrada == null){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        promocaoService.excluir(promocaoEncontrada);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(method=RequestMethod.PUT, value="/promocoes", consumes=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Promocao> alterarPromocao(@RequestBody Promocao promocao){
        Promocao promocaoAlterada = promocaoService.alterar(promocao);
        return new ResponseEntity<Promocao>(promocaoAlterada, HttpStatus.OK);
    }

}

Java

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;




@Entity
public class Promocao {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String produto;
    private double preco;
    private String marca;
    private String categoria;
    private String uniMedida;
    private String observacao;

    @Column(name = "dataInicio")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dataInicio;

    @Column(name = "dataFim")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dataFim;

    private String status;

    @JoinColumn
    @ManyToOne(cascade = CascadeType.REFRESH)
    private Usuario usuario;

    private String foto;






    public int getId() {
        return id;
    }

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

    public String getProduto() {
        return produto;
    }

    public void setProduto(String produto) {
        this.produto = produto;
    }

    public double getPreco() {
        return preco;
    }

    public void setPreco(double preco) {
        this.preco = preco;
    }

    public String getMarca() {
        return marca;
    }

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

    public String getCategoria() {
        return categoria;
    }

    public void setCategoria(String categoria) {
        this.categoria = categoria;
    }

    public String getUniMedida() {
        return uniMedida;
    }

    public void setUniMedida(String uniMedida) {
        this.uniMedida = uniMedida;
    }

    public String getObservacao() {
        return observacao;
    }

    public void setObservacao(String observacao) {
        this.observacao = observacao;
    }

    public Date getDataInicio() {
        return dataInicio;
    }

    public void setDataInicio(Date dataInicio) {
        this.dataInicio = dataInicio;
    }

    public Date getDataFim() {
        return dataFim;
    }

    public void setDataFim(Date dataFim) {
        this.dataFim = dataFim;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public String getFoto() {
        return foto;
    }

    public void setFoto(String foto) {
        this.foto = foto;
    } 






}

1 answer

1


Add the Spring @Datetimeformat annotation on the date fields. This annotation will convert the value of the date that comes as a form text to a java.util.Date object. Example:

@DateTimeFormat(iso = ISO.DATE_TIME)
@Column(name = "dataFim")
@Temporal(TemporalType.TIMESTAMP)
private Date dataFim;
  • I did it the way you suggested but still saving date as null in bank.

  • So, will the value of the date really be coming to server side? Checked this?

  • there were two problems: the first was a misguided statement in ng-model , the second was date formatting, I used the following method: app.directive("formatDate", function() {&#xA; return {&#xA; require: 'ngModel',&#xA; link: function(scope, elem, attr, modelCtrl) {&#xA; modelCtrl.$formatters.push(function(modelValue) {&#xA; if (modelValue){&#xA; return new Date(modelValue);&#xA; }&#xA; else {&#xA; return null;&#xA; }&#xA; });&#xA; }&#xA; };&#xA;});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.