How to insert record into database using spring jpa when there is no conflict

app :

I have spring boot application that is connected with the PostgreSQL database using spring-data-jpa, here is my entity with nearly 40 fields

Now for saving the entity into database, I'm just using the studentRepository.save method

studentRepository.save(new StudentEntity());

DAO Entity

  @Table
  @Entity
  public class StudentEntity {

     @Id
     @Generate( using database sequenece)
     private long studentId;

     private String studentName;

     private String dept;

     private String age;
      ..
      ..
      }

Repository

 public interface StudentRepository implements JPARepository<Long, Student> {
   }

But now I have requirement, if there is any student record in table with name and dept I should not insert the new record, I know I can use PostgreSQL ON CONFLICT with native query for this, but if I use native query I have to specify all 40 fields in query and as method arguments which looks ugly.

Is there any way to make it simpler?

Example of native query

@Query(value = "insert into Users (name, age, email, status) values (:name, :age, :email, :status)", nativeQuery = true)

 void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("status") Integer status, @Param("email") String email);
M. Deinum :

Use the database. Create a unique constraint on the 2 fields and trying to add multiple of those will be prevented.

Something like

ALTER TABLE StudentEntity ADD CONSTRAINT UQ_NAME_DEPT UNIQUE (studentName,dept);

This unique constraint will prevent the insertion of duplicate combinations.

You could also define an constraint on your JPA entity to automatically create the index for testing

@Table(uniqueConstraints=@UniqueConstraint(columnNames = {"studentName", "dept"})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75072&siteId=1