Problema com o jDateChooser na data

11 respostas
A

Olá

Estou com problemas ao inserir a data na minha base de dados usando o jDateChooser
Este é a parte do código

java.util.Date dataNasc = jDateChooser.getDate();
    java.sql.Date sqlDate = new java.sql.Date(dataNasc.getTime());
    System.out.println("utilDate:" + dataNasc);
    System.out.println("sqlDate:" + sqlDate); 
    users.setDataNasc(sqlDate);

O System.out.println dá-me o seguinte
utilDate:Fri Dec 18 00:00:00 GMT 2015
sqlDate:2015-12-18

Mas quando quero setar a data na minha entity(users) no debug aparece assim
18/dez/2015 0:00:00
Ou seja, como a minha base de dados só aceita aaaa-mm-dd, não grava

Alguma ajuda?

11 Respostas

P

O que tu imprimes é só uma forma de representar a data. O objeto Date em si não tem formato e pode ser impresso em qualquer formato.
Se o tipo de dados na Base de Dados é DATE, podes gravar com o objeto Date sem problemas. Se isso não funciona, mostra o código para se perceber o que estará mal.

A

Bom dia
Se ponho direto não grava, se ponho passando para sql não dá.
Quando carrego no botão o objetivo é que me grave um utilizador, este é o código do botão

private void novoUserBtActionPerformed(java.awt.event.ActionEvent evt) {                                           

    UsersService userService = new UsersService();
    Users users = new Users();
    if (!txtNome.getText().trim().equals("")) {
        java.util.Date dataNasc = jDateChooser.getDate();
        java.sql.Date sqlDate = new java.sql.Date(dataNasc.getTime());
        System.out.println("utilDate:" + dataNasc);
        System.out.println("sqlDate:" + sqlDate); 
        users.setDataNasc(sqlDate);
        users.setNome(txtNome.getText());     
        users.setEmail(txtEmail.getText());
        userService.persist(users);
    } else {
        error.setText("Deve preencher o campo Nome");
    }
}

Que chama o Userservices

public class UsersService {


private static UsersDao usersDao;
public UsersService() {
    usersDao = new UsersDao();
}

public void persist(Users entity) {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.persist(entity);
    usersDao.closeCurrentSessionwithTransaction();
}

E a classe principal

public class Users implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id_user")
private Integer idUser;
@Column(name = "nome")
private String nome;
@Column(name = "data_nasc")
@Temporal(TemporalType.DATE)
private Date dataNasc;
@Column(name = "email")
private String email;

Se a data não estiver no formato aaaa-mm-dd não grava

P

Que erro dá?

A

Não dá erro mas não grava por causa daquele formato porque o resto dos campos (nome e email) são passados corretamente.
O problema está na data

P

Não dá erro? Estás a fazer commit? Se não colocares nenhuma data grava?

A

Vou tentar, volto ao meio dia já que estou numa formação, até já

C

@alphasil venho reforçar o que o nosso colega @pmlm já dize no java não importa o formato importa o objeto ser do tipo date, na hora de persistir o framework de persistencia vai saber fazer a persistencia da informação.

O que notei de diferente do que eu uso é que você usou o java.sql.Date eu sempre uso nas minhas entidades o java.util.Date.

Oberse o log algum erro ou alguma informação relevante deve estar sendo printado, caso não consigua identificar nada, poste o log completo aqui para nos olharmos e ver se conseguimos identificar alguma coisa.

Volto a reforçar no java o formato da data não é importante para persistir, o que é necessário é o objeto na entidade ser do tipo Date e no banco de dados tambem ser do tipo date, timestamp, ou seja, deve ser qualquer tipo que sirva para armazenar datas.

A

De volta
Bem estive a tentar o que o colega “pmlm” me pediu e efetivamente nada é gravado sem o cmapo data por isso devo ter alguma coisa mal pelo meio.
O que me aparece no output é isto
dez 16, 2015 11:13:42 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
dez 16, 2015 11:13:42 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
dez 16, 2015 11:13:43 AM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
dez 16, 2015 11:13:43 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
dez 16, 2015 11:13:43 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
dez 16, 2015 11:13:43 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
INFO: HHH000397: Using ASTQueryTranslatorFactory
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata
INFO: HHH000261: Table found: esmaior_secretaria.users
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata
INFO: HHH000037: Columns: [nome, id_user, data_nasc, email]
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata
INFO: HHH000108: Foreign keys: []
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete

Não vejo erro

Class Users

Entity
@Table(name = users)

@XmlRootElement

public class Users implements Serializable {

@Transient

private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);

private static final long serialVersionUID = 1L;

@Id

@Column(name = id_user)

private Integer idUser;

@Column(name = nome)

private String nome;

@Column(name = data_nasc)

@Temporal(TemporalType.DATE)

private Date dataNasc;

@Column(name = email)

private String email;
public Users() {
}

public Users(Integer idUser) {
    this.idUser = idUser;
}

public Users(Integer idUser, String nome, Date dataNasc, String email) {
    this.idUser = idUser;
    this.nome = nome;
    this.dataNasc = dataNasc;
    this.email = email;
}

public Integer getIdUser() {
    return idUser;
}

public void setIdUser(Integer idUser) {
    Integer oldIdUser = this.idUser;
    this.idUser = idUser;
    changeSupport.firePropertyChange("idUser", oldIdUser, idUser);
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    String oldNome = this.nome;
    this.nome = nome;
    changeSupport.firePropertyChange("nome", oldNome, nome);
}

public Date getDataNasc() {
    return dataNasc;
}

public void setDataNasc(Date dataNasc) {
    Date oldDataNasc = this.dataNasc;
    this.dataNasc = dataNasc;
    changeSupport.firePropertyChange("dataNasc", oldDataNasc, dataNasc);
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    String oldEmail = this.email;
    this.email = email;
    changeSupport.firePropertyChange("email", oldEmail, email);
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (idUser != null ? idUser.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 Users)) {
        return false;
    }
    Users other = (Users) object;
    if ((this.idUser == null && other.idUser != null) || (this.idUser != null && !this.idUser.equals(other.idUser))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "gmc.esmaior.model.Users[ idUser=" + idUser + " ]";
}

public void addPropertyChangeListener(PropertyChangeListener listener) {
    changeSupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    changeSupport.removePropertyChangeListener(listener);
}

}

Class UsersDao

public class UsersDao implements UsersDAOInterface<Users, String> {

private Session currentSession;
private Transaction currentTransaction;

public Session openCurrentSession() {
    currentSession = getSessionFactory().openSession();
    return currentSession;
}

public Session openCurrentSessionwithTransaction() {
    currentSession = getSessionFactory().openSession();
    currentTransaction = currentSession.beginTransaction();
    return currentSession;
}

public void closeCurrentSession() {
    currentSession.close();
}

public void closeCurrentSessionwithTransaction() {
    currentTransaction.commit();
    currentSession.close();
}

private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

public Session getCurrentSession() {
    return currentSession;
}

public void setCurrentSession(Session currentSession) {
    this.currentSession = currentSession;
}

public Transaction getCurrentTransaction() {
    return currentTransaction;
}

public void setCurrentTransaction(Transaction currentTransaction) {
    this.currentTransaction = currentTransaction;
}

public void persist(Users entity) {
    try {
        getCurrentSession().save(entity);
    } catch (Exception e) {
    }
}

public void update(Users entity) {
    try {
        getCurrentSession().update(entity);
    } catch (Exception e) {
    }
}

public Users findById(String id) {
    Users users = (Users) getCurrentSession().get(Users.class, id);
    return users;
}

public void delete(Users entity) {
    getCurrentSession().delete(entity);

}

@SuppressWarnings("unchecked")
public List<Users> findAll() {
    List<Users> users = (List<Users>) getCurrentSession().createQuery("from Users").list();
    return users;
}

public void deleteAll() {
    List<Users> entityList = findAll();
    for (Users entity : entityList) {
        delete(entity);
    }

}

public List<Users> aniversariosByDate() {
    List<Users> users = (List<Users>) getCurrentSession().createQuery("from Users k where month(k.dataNasc)=month(current_date()) and day(k.dataNasc)=day(current_date())").list();
    return users;
}

}

Classe UsersDAOInterface

public interface UsersDAOInterface<T, Id extends Serializable> {
public void persist(T entity);
public void update(T entity);
public T findById(Id id);
public void delete(T entity);
public List<T> findAll();
public void deleteAll(); 
public List<T> aniversariosByDate();

}

E por fim Classe Service

public class UsersService {


private static UsersDao usersDao;
public UsersService() {
    usersDao = new UsersDao();
}

public void persist(Users entity) {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.persist(entity);
    usersDao.closeCurrentSessionwithTransaction();
}

public void update(Users entity) {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.update(entity);
    usersDao.closeCurrentSessionwithTransaction();
}

public Users findById(String id) {
    usersDao.openCurrentSession();
    Users usersId = usersDao.findById(id);
    usersDao.closeCurrentSession();
    return usersId;
}

public void delete(String id) {
    usersDao.openCurrentSessionwithTransaction();
    Users users = usersDao.findById(id);
    usersDao.delete(users);
    usersDao.closeCurrentSessionwithTransaction();
}

public List<Users> findAll() {
    usersDao.openCurrentSession();
    List<Users> users = usersDao.findAll();
    usersDao.closeCurrentSession();
    return users;
}

public void deleteAll() {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.deleteAll();
    usersDao.closeCurrentSessionwithTransaction();
}

public List<Users> aniversarios(){
    usersDao.openCurrentSession();
    List<Users> aniversarios = usersDao.aniversariosByDate();
    usersDao.closeCurrentSession();
    return aniversarios;
}

public UsersDao usersDao() {
    return usersDao;
}

}

E para criar um registo uso

private void novoUserBtActionPerformed(java.awt.event.ActionEvent evt) {                                           

    UsersService userService = new UsersService();
    Users users = new Users();
    if (!txtNome.getText().trim().equals("")) {
        users.setNome(txtNome.getText());     
        users.setEmail(txtEmail.getText());
        userService.persist(users);
    } else {
        error.setText("Deve preencher o campo Nome");
    }
}

Se não me grava mesmo sem data é porque há algo aqui que não deve estar bem…

A

De volta
Bem estive a tentar o que o colega “pmlm” me pediu e efetivamente nada é gravado sem o cmapo data por isso devo ter alguma coisa mal pelo meio.
O que me aparece no output é isto

<strong>org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): gmc.esmaior.model.Users</strong>

dez 16, 2015 11:13:42 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator

INFO: HHH000006: Autocommit mode: false

dez 16, 2015 11:13:42 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure

INFO: HHH000115: Hibernate connection pool size: 20 (min=1)

dez 16, 2015 11:13:43 AM org.hibernate.dialect.Dialect 

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect

dez 16, 2015 11:13:43 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation

INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4

dez 16, 2015 11:13:43 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)

dez 16, 2015 11:13:43 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 

INFO: HHH000397: Using ASTQueryTranslatorFactory

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute

INFO: HHH000228: Running hbm2ddl schema update

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute

INFO: HHH000102: Fetching database metadata

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute

INFO: HHH000396: Updating schema

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata 

INFO: HHH000261: Table found: esmaior_secretaria.users

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata 

INFO: HHH000037: Columns: [nome, id_user, data_nasc, email]

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata 

INFO: HHH000108: Foreign keys: []

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.TableMetadata 

INFO: HHH000126: Indexes: [primary]

dez 16, 2015 11:13:43 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute

INFO: HHH000232: Schema update complete

Não vejo erro

Class Users

@Entity
@Table(name = "users")
@XmlRootElement
public class Users implements Serializable {
    @Transient
    private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "id_user")
    private Integer idUser;
    @Column(name = "nome")
    private String nome;
    @Column(name = "data_nasc")
    @Temporal(TemporalType.DATE)
    private Date dataNasc;
    @Column(name = "email")
    private String email;

    public Users() {
    }

    public Users(Integer idUser) {
        this.idUser = idUser;
    }

    public Users(Integer idUser, String nome, Date dataNasc, String email) {
        this.idUser = idUser;
        this.nome = nome;
        this.dataNasc = dataNasc;
        this.email = email;
    }

    public Integer getIdUser() {
        return idUser;
    }

    public void setIdUser(Integer idUser) {
        Integer oldIdUser = this.idUser;
        this.idUser = idUser;
        changeSupport.firePropertyChange("idUser", oldIdUser, idUser);
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        String oldNome = this.nome;
        this.nome = nome;
        changeSupport.firePropertyChange("nome", oldNome, nome);
    }

    public Date getDataNasc() {
        return dataNasc;
    }

    public void setDataNasc(Date dataNasc) {
        Date oldDataNasc = this.dataNasc;
        this.dataNasc = dataNasc;
        changeSupport.firePropertyChange("dataNasc", oldDataNasc, dataNasc);
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        String oldEmail = this.email;
        this.email = email;
        changeSupport.firePropertyChange("email", oldEmail, email);
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idUser != null ? idUser.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 Users)) {
            return false;
        }
        Users other = (Users) object;
        if ((this.idUser == null && other.idUser != null) || (this.idUser != null && !this.idUser.equals(other.idUser))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "gmc.esmaior.model.Users[ idUser=" + idUser + " ]";
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        changeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        changeSupport.removePropertyChangeListener(listener);
    }

}

Class UsersDao

public class UsersDao implements UsersDAOInterface<Users, String> {

private Session currentSession;
private Transaction currentTransaction;

public Session openCurrentSession() {
    currentSession = getSessionFactory().openSession();
    return currentSession;
}

public Session openCurrentSessionwithTransaction() {
    currentSession = getSessionFactory().openSession();
    currentTransaction = currentSession.beginTransaction();
    return currentSession;
}

public void closeCurrentSession() {
    currentSession.close();
}

public void closeCurrentSessionwithTransaction() {
    currentTransaction.commit();
    currentSession.close();
}

private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

public Session getCurrentSession() {
    return currentSession;
}

public void setCurrentSession(Session currentSession) {
    this.currentSession = currentSession;
}

public Transaction getCurrentTransaction() {
    return currentTransaction;
}

public void setCurrentTransaction(Transaction currentTransaction) {
    this.currentTransaction = currentTransaction;
}

public void persist(Users entity) {
    try {
        getCurrentSession().save(entity);
    } catch (Exception e) {
    }
}

public void update(Users entity) {
    try {
        getCurrentSession().update(entity);
    } catch (Exception e) {
    }
}

public Users findById(String id) {
    Users users = (Users) getCurrentSession().get(Users.class, id);
    return users;
}

public void delete(Users entity) {
    getCurrentSession().delete(entity);

}

@SuppressWarnings("unchecked")
public List<Users> findAll() {
    List<Users> users = (List<Users>) getCurrentSession().createQuery("from Users").list();
    return users;
}

public void deleteAll() {
    List<Users> entityList = findAll();
    for (Users entity : entityList) {
        delete(entity);
    }

}

public List<Users> aniversariosByDate() {
    List<Users> users = (List<Users>) getCurrentSession().createQuery("from Users k where month(k.dataNasc)=month(current_date()) and day(k.dataNasc)=day(current_date())").list();
    return users;
}

}

Classe UsersDAOInterface

public interface UsersDAOInterface<T, Id extends Serializable> {
public void persist(T entity);
public void update(T entity);
public T findById(Id id);
public void delete(T entity);
public List<T> findAll();
public void deleteAll(); 
public List<T> aniversariosByDate();

}

E por fim Classe Service

public class UsersService {


private static UsersDao usersDao;
public UsersService() {
    usersDao = new UsersDao();
}

public void persist(Users entity) {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.persist(entity);
    usersDao.closeCurrentSessionwithTransaction();
}

public void update(Users entity) {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.update(entity);
    usersDao.closeCurrentSessionwithTransaction();
}

public Users findById(String id) {
    usersDao.openCurrentSession();
    Users usersId = usersDao.findById(id);
    usersDao.closeCurrentSession();
    return usersId;
}

public void delete(String id) {
    usersDao.openCurrentSessionwithTransaction();
    Users users = usersDao.findById(id);
    usersDao.delete(users);
    usersDao.closeCurrentSessionwithTransaction();
}

public List<Users> findAll() {
    usersDao.openCurrentSession();
    List<Users> users = usersDao.findAll();
    usersDao.closeCurrentSession();
    return users;
}

public void deleteAll() {
    usersDao.openCurrentSessionwithTransaction();
    usersDao.deleteAll();
    usersDao.closeCurrentSessionwithTransaction();
}

public List<Users> aniversarios(){
    usersDao.openCurrentSession();
    List<Users> aniversarios = usersDao.aniversariosByDate();
    usersDao.closeCurrentSession();
    return aniversarios;
}

public UsersDao usersDao() {
    return usersDao;
}

}

E para criar um registo uso

private void novoUserBtActionPerformed(java.awt.event.ActionEvent evt) {                                           

    UsersService userService = new UsersService();
    Users users = new Users();
    if (!txtNome.getText().trim().equals("")) {
        users.setNome(txtNome.getText());     
        users.setEmail(txtEmail.getText());
        userService.persist(users);
    } else {
        error.setText("Deve preencher o campo Nome");
    }
}

Se não me grava mesmo sem data é porque há algo aqui que não deve estar bem…

P

O teu problema está aqui então. Tens de definir o id do User ou ter um generator que defina esse id.

A

Boda tarde!
Bem, não sei se entendi muito a pergunta, pelo que vi, você não está buscando de forma correta o valor, mas tente usar esse código aqui para conseguir o valor da data da sua JDateChooser:

`// data com hora dd/mm/yyy hh:mm:ss
java.sql.Timestamp timestamp = new Timestamp(jDateChooser.getDate().getTime());

//apenas data dd/mm/yyyy
new java.sql.Date date = new java.sql.Date(jDateChooser.getDate().getTime());`

:wink:

Criado 15 de dezembro de 2015
Ultima resposta 23 de dez. de 2015
Respostas 11
Participantes 4