Java

Ya hemos visto en artículos anteriores como empezar con JPA en JAVA y las ventajas que nos trae hacer uso de esta API de persistencias, a continuación veamos como podemos realizar una inserción de una base de datos de un formulario haciendo uso de JPA para insertar los datos (Insert Java Mysql) usando POO y de forma muy fácil:

Insert Java Mysql JPA (Java Persitence Api)

Un formulario de ejemplo:

formulario java

Método para validar y registrar:

🌟 ¡Visita Nuestra Tienda para Programadores! 🌟

Descubre Códigos Fuente, Cursos, Software, Computadoras, Accesorios y Regalos Exclusivos. ¡Todo lo que necesitas para llevar tu programación al siguiente nivel!


private void Registrar_Cliente(){
try {
if (!identificacion.getText().isEmpty()) {
if (!nombres.getText().isEmpty()) {
if (Funciones.getFecha(jDateChooser1) != null) {
if (!direccion.getText().isEmpty()) {
if (!telefono.getText().isEmpty()) {
Clientes cli = new Clientes();
cli.setIdentificacion(identificacion.getText());
cli.setNombres(nombres.getText());
cli.setApellidos(apellidos.getText());
cli.setFechaNac(stringToDate(getFecha(jDateChooser1)));
cli.setDireccion(direccion.getText());
cli.setOcupacion(ocupacion.getText());
cli.setTelefono(telefono.getText());
cli.setEmail(email.getText());
cli.setEstado('1');
CClientes.create(cli); //Controlador Cliente
JOptionPane.showMessageDialog(this, "El cliente fué registrado con éxito");
Limpiar();
} else {
JOptionPane.showMessageDialog(this, "Por favor ingrese un teléfono");
telefono.requestFocusInWindow();
}
} else {
JOptionPane.showMessageDialog(this, "Por favor ingrese una dirección");
direccion.requestFocusInWindow();
}
} else {
JOptionPane.showMessageDialog(this, "Por favor ingrese una fecha válida");
}
} else {
JOptionPane.showMessageDialog(this, "Por favor ingrese un nombre");
nombres.requestFocusInWindow();
}
} else {
JOptionPane.showMessageDialog(this, "Por favor ingrese una identificación");
identificacion.requestFocusInWindow();
}
} catch (HeadlessException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}

Métodos que intervienen en el proceso:


public java.util.Date stringToDate(String fecha) {
SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd");
Date fechaEnviar = null;
try {
fechaEnviar = formatoDelTexto.parse(fecha);
return fechaEnviar;
} catch (ParseException ex) {
ex.printStackTrace();
return null;
}
}


SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");

public String getFecha(JDateChooser jd) {
if (jd.getDate() != null) {
return yyyyMMdd.format(jd.getDate());
} else {
return null;
}
}

🎯 ¿Quieres dominar la programación y estar siempre un paso adelante?

¡No te pierdas los mejores tutoriales, consejos y herramientas para desarrolladores como tú! 💻
Suscríbete ahora a mi canal de YouTube y únete a una comunidad que aprende y crece cada día. 🚀

👉 Haz clic aquí para suscribirte

¡Es gratis y tu próxima habilidad está a un clic de distancia! 🧠🔥

Entidad Cliente:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Entidades;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
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.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlTransient;

/**
*
* @author Ivan
*/
@Entity
@Table(name = «clientes»)
public class Clientes implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = «id»)
private Integer id;
@Column(name = «identificacion»)
private String identificacion;
@Column(name = «nombres»)
private String nombres;
@Column(name = «apellidos»)
private String apellidos;
@Column(name = «fecha_nac»)
@Temporal(TemporalType.DATE)
private Date fechaNac;
@Column(name = «direccion»)
private String direccion;
@Column(name = «ocupacion»)
private String ocupacion;
@Column(name = «telefono»)
private String telefono;
@Column(name = «email»)
private String email;
@Column(name = «estado»)
private Character estado;

public Clientes() {
}

public Clientes(Integer id) {
this.id = id;
}

public Integer getId() {
return id;
}

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

public String getIdentificacion() {
return identificacion;
}

public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}

public String getNombres() {
return nombres;
}

public void setNombres(String nombres) {
this.nombres = nombres;
}

public String getApellidos() {
return apellidos;
}

public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}

public Date getFechaNac() {
return fechaNac;
}

public void setFechaNac(Date fechaNac) {
this.fechaNac = fechaNac;
}

public String getDireccion() {
return direccion;
}

public void setDireccion(String direccion) {
this.direccion = direccion;
}

public String getOcupacion() {
return ocupacion;
}

public void setOcupacion(String ocupacion) {
this.ocupacion = ocupacion;
}

public String getTelefono() {
return telefono;
}

public void setTelefono(String telefono) {
this.telefono = telefono;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public Character getEstado() {
return estado;
}

public void setEstado(Character estado) {
this.estado = estado;
}

@XmlTransient
public List getMotosList() {
return motosList;
}

public void setMotosList(List motosList) {
this.motosList = motosList;
}

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

@Override
public String toString() {
return «Entidades.Clientes[ id=» + id + » ]»;
}

}

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *