-2

So I've been working on our project in Programming and it has something to do with adding product. Now, my AddProduct codes work however I would like to insert a code where in if I add the same name of the product that is already in the database then it will appear a Jdialog saying this product has been added already then the code will not add the product name on the database but if the name doesn't yet exists on the database then it will appear a Jdialog saying this product has been added to the database then the code will add the product name on database

The problem is I don't have any idea about the codes that I will use. Should I use if-else statement? Then if yes? How? Please I badly need your help Thank you so much

2 Answers2

1

use unique=true in your entity class;

@Entity
public class Employee {
 @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "username" , unique = true)
private String username;
//// constructors
//// getters and setters
}

and in the controller if the user name already presents in the database it throws exception, catch the exception and show the message as value already exists in db.

@RestController
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;

@Autowired
public EmployeeController(EmployeeRepository employeeRepository) {
    this.employeeRepository = employeeRepository;
}

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@RequestBody Employee employee) {
    try {
        employeeRepository.save(employee);
        return "employee added successfully";
    } catch (DataIntegrityViolationException e) {

        String employeename = employee.getUsername();
        return "employee named " + employeename + " already exists";
    }
}

and add the repository interface

@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
List<Employee> findById(long id);
List<Employee> findByUsername(String username);

}
  • Interesting idea but in a general way, you may have other constraints in your tables and the sql error may be so other thing than a duplicated username. Catching `DataIntegrityViolationException` is probably not the best solution since it may have side effect. – davidxxx Dec 10 '16 at 11:04
0

You have to use map format structure in that data is in key and data format for specific data that you want to add prepare key base on your product name and save it whenever you have to insert any item then only scan the key if its find similar then add msg that the data is already present & if not then insert into it

Rhushi
  • 1
  • 1