Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a new row using JpaRepository in java

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.

like image 808
mary_jane Avatar asked Oct 05 '17 17:10

mary_jane


3 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.

like image 80
blue_note Avatar answered Nov 17 '22 18:11

blue_note


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);
like image 41
ahmetcetin Avatar answered Nov 17 '22 17:11

ahmetcetin


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);
}
like image 39
Madhu Reddy Avatar answered Nov 17 '22 16:11

Madhu Reddy