Insert a new row using JpaRepository in java

Viewed 30487

I am very new to spring JPA. I have following entity class which I want to insert in table:

@Entity
@Table(name = "test")
public class Test {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "user")
    private String user;
}

I have an empty table named test. I have multiple objects of Test and I want to insert it to the table. For this I have created a repo class:

@Repository("testRepo")
public interface TestRepo extends JpaRepository<Test, String> {
//write insert query    
    @Modifying
    @Query(//What insert query I should write)
    void insertData(@Param("id") String id);

}

I have searched but getting only options for update query.

4 Answers

The method .save(Entity entity), inherited from the Parent interface CrudRepository can be used to both update an existing entity or create a new one.

Your repository interface extends from JpaRepository which extends from CrudRepository. save and saveAndFlush methods can be used as default to insert new rows.

save: Inserts new rows. You can give row list as parameter to this method. In your example it should be used like this:

testRepo.save(testEntity);

or

testRepo.save(testEntities);

saveAndFlush: Inserts only a new row and commit the changes immediately. In your example it should be used like this:

testRepo.saveAndFlush(testEntity);

In your service class do something similar to below. You don't have to write a separate method to save the entity. save method of the repository can be used to save the entity.

class TestDAO{

@Autowired
TestRepo testRepo;

public void saveTest(Test test) {
testRepo.save(test);
}

("insert into table values (?1)",nativeQuery = true)

Related