CRUD – Spring Boot + ReactJS + API Rest + MySQL #11 Entity Job

Spring – Backend

Controller

src/main/java/com/tutofox/demo/controllers/EmployeeController.java

package com.tutofox.tutospring.controllers;
/.../
import javax.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
	
  /.../
	
	@GetMapping(value="/job")
	public List<Job> listJob(){
		List<Job> listJob;
		listJob = employeeRepository.findAllJob(); 
		return listJob;
	}

	 
}

Repository

src/main/java/com/tutofox/demo/controllers/src/main/java/com/tutofox/tutospring/repository/EmployeeRepository.java.java

package com.tutofox.tutospring.repository;

import java.util.List;
import java.util.Optional;
 
import org.springframework.data.jpa.repository.Query;
import com.tutofox.tutospring.models.Job;

public interface EmployeeRepository extends JpaRepository<Employee, Integer>{

	/.../
  
	@Query("from Job")
	List<Job> findAllJob();
 
 
}

Model

src/main/java/com/tutofox/tutospring/models/Employee.java

package com.tutofox.tutospring.models;

/.../
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Email;
 
 

@Entity 
@Table(name="employee")
public class Employee {
	
   /.../
          
    @NotNull(message = "The job is required")
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "job")
	@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
	private Job job;
	

	public Job getJob() {
		return job;
	}

	public void setJob(Job job) {
		this.job = job;
	}
	 

}

src/main/java/com/tutofox/tutospring/models/Job.java

package com.tutofox.tutospring.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity 
@Table(name="job")
public class Job {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	
	@Column(name = "job_name")
	private String name;

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	 
	
}

ReactJS – Frontend

Services Employee

src/main/resources/js/components/services/Employee.js

const baseUrl = "http://localhost:8080/api/employee"
import axios from "axios";
const employee = {};

employee.listJob = async () => {
  const urlList = baseUrl+"/job"
  const res = await axios.get(urlList)
  .then(response => { return response.data })
  .catch(error=>{ return error })
  return res;
}

employee.update = async (state) => {

  const datapost = {
    name: state.fieldName,
    email: state.fieldEmail,
    phone: state.fieldPhone,
    address: state.fieldAddress,
    job: JSON.parse(state.selectJob)
  }

  const urlUpdate = baseUrl+"/update/"+state.id

  const res = await axios.put(urlUpdate,datapost)
  .then(response=>{ return response.data })
  .catch(error=>{ return error.response })

  return res;
}

employee.create = async (state) => {

  const datapost = {
    name: state.fieldName,
    email: state.fieldEmail,
    phone: state.fieldPhone,
    address: state.fieldAddress,
    job: JSON.parse(state.selectJob)
  }

  const urlPost = baseUrl+"/create"

  const res = await axios.post(urlPost,datapost)
  .then(response=>{ return response.data; })
  .catch(error=>{ return error.response; })

  return res;
}


export default employee

Select

<div class="row">
          <div class="col-md-6 mb-3">
						<label for="phone">Job </label>
						<select id="inputState" class="form-control" onChange={(event)=> this.setState({selectJob:event.target.value})}>
	             <option selected>Choose...</option>
							 {
								 this.state.listJob.map((select)=>{
									 return(
										 <option value={JSON.stringify(select)}>{select.name}</option>
									 )
								 })
							 }
	          </select>
          </div>
        </div>

Form

src/main/resources/js/components/employee/Form.js

import React, { Component } from 'react';

import employeeServices from "../services/Employee"

export default class Form extends Component {

	constructor(){
		super();
		this.state = {
			fieldName:"",
			fieldEmail:"",
			fieldAddress:"",
			fieldPhone:"",
			errorField:[],
			selectJob:{},
			listJob:[]
		}
	}

	componentDidMount(){
     this.setListJob()
  }

	async setListJob()
	{
		employeeServices.listJob().then((res)=>{ this.setState({listJob:res}) })
	}

  render() {
    return (
      <div>
      	<h4>Create employee v2 </h4>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="firstName">Name employee</label>
            <input type="text" class="form-control" placeholder="Name"
            	value={this.state.fieldName}
            	onChange={(event)=>this.setState({fieldName:event.target.value})}
            	/>
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="email">Email</label>
	          <input type="email" class="form-control" placeholder="[email protected]"
	        	  value={this.state.fieldEmail}
          		  onChange={(event)=>this.setState({fieldEmail:event.target.value})}
	        	  />
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="address">Address</label>
	          <input type="text" class="form-control" placeholder="1234 Main St"
							value={this.state.fieldAddress}
							onChange={(event)=>this.setState({fieldAddress:event.target.value})}
						/>
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="phone">Phone </label>
	          <input type="text" class="form-control" placeholder="123467890"
							value={this.state.fieldPhone}
							onChange={(event)=>this.setState({fieldPhone:event.target.value})}
						/>
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="phone">Job </label>
						<select id="inputState" class="form-control" onChange={(event)=> this.setState({selectJob:event.target.value})}>
	             <option selected>Choose...</option>
							 {
								 this.state.listJob.map((select)=>{
									 return(
										 <option value={JSON.stringify(select)}>{select.name}</option>
									 )
								 })
							 }
	          </select>
          </div>
        </div>

				{
					this.state.errorField.map((itemerror)=>{
						return(
							<p class="text-danger">*{itemerror}</p>
						)
					})
				}

				<div class="row">
					<div class="col-md-6 mb-3">
		      	<button onClick={()=>this.onClickSave()} class="btn btn-primary btn-block" type="submit">Save</button>
					</div>
				</div>
      </div>
    )
  }

	async onClickSave()
	{
		const res = await employeeServices.create(this.state)
		if (res.success) {
			alert(res.message)
			console.log(res);
			// window.location.replace("/employee/index")
		}
		else if (res.status==400) {
			console.log(res.status);
			const dataError = []
			const error = res.data.errors

			if (error) {
				error.map((itemerror)=>{
					console.log(itemerror.defaultMessage);
					dataError.push(itemerror.defaultMessage)
				})
				this.setState({errorField:dataError})
			}
			else {
				dataError.push(res.data.message)
				this.setState({errorField:dataError})
			}
		}
		else {
			// alert("Error ==>"+JSON.stringify(res))
			console.log(res);
			const dataError = []
			dataError.push(res.message);
			this.setState({errorField:dataError});
		}
	}

}

Edit

src/main/resources/js/components/employee/Edit.js

import React, { Component } from 'react';

import employeeServices from "../services/Employee"

export default class Edit extends Component {

  constructor(){
    super()
    this.state = {
      id:0,
      fieldName:"",
      fieldEmail:"",
      fieldPhone:"",
      fieldAddress:"",
      selectJob:{},
			listJob:[],
    }
  }

  async componentDidMount()
  {
    console.log("Mounted edit");
    this.setListJob()
    const id = this.props.match.params.id;
    const res = await employeeServices.get(id)
    console.log(res);
    if (res.success) {
      console.log(res.data);
      this.setState({
        id:res.data.id,
        fieldName:res.data.name,
        fieldEmail:res.data.email,
        fieldAddress:res.data.address,
        fieldPhone:res.data.phone,
        selectJob:res.data.job
      })
    }
    else {
      alert("Error ==>"+res.message)
    }
  }

  async setListJob()
	{
		employeeServices.listJob().then((res)=>{ this.setState({listJob:res}) })
	}

  render() {
    let userId = this.props.match.params.id;
    return (
      <div>
        <h4>Edit employee {userId} v2 </h4>
        <hr />
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="firstName">Name employee</label>
            <input type="text" class="form-control"
              value={this.state.fieldName}
              onChange={(event)=>this.setState({fieldName:event.target.value})}
            />
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="email">Email</label>
	          <input type="email" class="form-control" placeholder="[email protected]"
            value={this.state.fieldEmail}
            onChange={(event)=>this.setState({fieldEmail:event.target.value})}
            />
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="address">Address</label>
	          <input type="text" class="form-control" placeholder="1234 Main St"
            value={this.state.fieldAddress}
            onChange={(event)=>this.setState({fieldAddress:event.target.value})}
            />
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="address">Phone </label>
	          <input type="text" class="form-control" placeholder="123467890"
              value={this.state.fieldPhone}
              onChange={(event)=>this.setState({fieldPhone:event.target.value})}
            />
          </div>
        </div>

        <div class="row">
          <div class="col-md-6 mb-3">
						<label for="phone">Job </label>
						<select id="inputState" class="form-control" onChange={(event)=> this.setState({selectJob:event.target.value})}>
	             <option selected>{this.state.selectJob.name}</option>
							 {
								 this.state.listJob.map((select)=>{
									 return(
										 <option value={JSON.stringify(select)}>{select.name}</option>
									 )
								 })
							 }
	          </select>
          </div>
        </div>

				<div class="row">
					<div class="col-md-6 mb-3">
		      	<button onClick={()=>this.onClickUpdate()}
            class="btn btn-primary btn-block" type="submit">Update</button>
					</div>
				</div>
      </div>
    )
  }

  async onClickUpdate(){

    console.log("Execute update");
    const res = await employeeServices.update(this.state)
    if (res.success) {
      alert(res.message)
    }
    else {
      console.log("Error");
      console.log(res);
      alert("Error ===>"+JSON.stringify(res.data))
    }
  }

}

List

src/main/resources/js/components/employee/List.js

import React, { Component } from 'react';

import employeeServices from "../services/Employee"
import { Link } from "react-router-dom"

export default class List extends Component {

  constructor()
  {
    super()
    this.state = {
      listEmployee:[]
    }
  }

  async componentDidMount(){
    console.log("Mounted List");
    const res = await employeeServices.list()
    console.log(res);
    if (res.success) {
      this.setState({listEmployee:res.list})
    }
    else {
      alert("Error server ==>"+JSON.stringify(res))
    }
  }

  render() {
    return (
      <section>
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Address</th>
              <th scope="col">Phone</th>
              <th scope="col">Job</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody>

            {
              this.state.listEmployee.map((data,i)=>{
                return(
                  <tr>
                    <th scope="row">{data.id}</th>
                    <td>{data.name}</td>
                    <td>{data.email}</td>
                    <td>{data.address}</td>
                    <td>{data.phone}</td>
                    <td>{data.job.name}</td>
                    <td>
                      <Link to={"/employee/edit/"+data.id} class="btn btn-light"> Edit </Link>
                      <a onClick={()=>this.onClickDelete(i,data.id)}
                      href="#" class="btn btn-danger"> Delete </a>
                    </td>
                  </tr>
                )
              })
            }
          </tbody>
        </table>
      </section>
    )
  }

  async onClickDelete(index,id)
  {
      var yes = confirm("Are you sure to delete this item?")

      if (yes===true) {

        const res = await employeeServices.delete(id)

        if (res.success) {
          alert(res.message)
          const list = this.state.listEmployee
          list.splice(index,1)
          this.setState({listEmployee:list})
        }
        else {
          alert("Error server ==> "+JSON.stringify(res))
        }
      }
  }

}

Deja una respuesta

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