在 java 中使用 JpaRepository 插入新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46591924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:17:16  来源:igfitidea点击:

Insert a new row using JpaRepository in java

javamysqlspringspring-data-jpa

提问by oxy_js

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

我对 spring JPA 很陌生。我有以下要插入表中的实体类:

@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:

我有一个名为test. 我有多个 Test 对象,我想将其插入表中。为此,我创建了一个 repo 类:

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

我已经搜索过但只获得更新查询的选项。

采纳答案by Madhu Reddy

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.

在您的服务类中执行类似于下面的操作。您不必编写单独的方法来保存实体。可以使用存储库的 save 方法来保存实体。

class TestDAO{

@Autowired
TestRepo testRepo;

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

回答by blue_note

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

.save(Entity entity)从 Parent 接口继承的方法CrudRepository可用于更新现有实体或创建新实体。

回答by ahmetcetin

Your repository interface extends from JpaRepository which extends from CrudRepository. saveand saveAndFlushmethods can be used as default to insert new rows.

您的存储库接口从 JpaRepository 扩展,后者从 CrudRepository 扩展。savesaveAndFlush方法可用作默认插入新行。

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:

saveAndFlush:仅插入新行并立即提交更改。在您的示例中,它应该像这样使用:

testRepo.saveAndFlush(testEntity);