9

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.

1
  • This is Spring Data JPA (!= JPA API) Commented Oct 6, 2017 at 6:58

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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);

Comments

1

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);
}

Comments

1

Using spring boot 2.7.5 I'm using JPA Repository with this for instance:

    @Query("INSERT INTO Planeta p (nome, clima, terreno) VALUES (:nome, :clima, :terreno)")
    Integer insertPlaneta(String nome, String clima, String terreno);

Parameters are passed with :name_of_parameter according with parameters method.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.