user16229573
user16229573

Reputation:

Is it possible to apply Save All Method as insert ignore method in JPA Repository?

I'm spring boot newbie so my knowledge is lacking.

I am using MySql with JPA repository in spring boot.

I put the data in an ArrayList and saved it using the "SaveAll" method.

I am trying to save by "insert ignore" method due to data conflict problem, is it possible?

Batch insert has been set and is being used.

Upvotes: 4

Views: 7854

Answers (2)

soung
soung

Reputation: 1614

Adding a custom insert query is very easy to do in Spring Data JPA. All we have to do is to annotate the entity with @SQLInsert. And jpa repositories save and saveAll will take this insert query in consideration.

find here some documentation

Code sample :

import org.hibernate.annotations.SQLInsert;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

@Entity
@Table(name = "users")
@SQLInsert(sql = "INSERT IGNORE INTO users(first_name, last_name, email) " +
        "VALUES (?, ?, ?)" )
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "first_name", nullable = false)
    @NotBlank
    @Size(max = 512)
    private String firstName;

    @Column(name = "last_name", nullable = false)
    @NotBlank
    @Size(max = 512)
    private String lastName;

    @Column(nullable = false)
    @NotBlank
    @Email
    @Size(max = 512)
    private String email;

But in my Opinion it is better to use native query for insertions

Upvotes: 2

turbofood
turbofood

Reputation: 322

You could use an @Query annotation to define your own custom repo method to accomplish this

@Query("INSERT IGNORE INTO table (COLUMNS) values (...)")
public List<S> saveAllInsertIgnore(List<> list);

Upvotes: 0

Related Questions