【问题标题】:CrudRepository save method doesnt save any in dbCrudRepository 保存方法不保存任何数据库
【发布时间】:2020-07-03 20:13:19
【问题描述】:

我的行为很奇怪。我创建了扩展 CrudRepository 的存储库。除保存方法外,所有默认方法都可以正常工作。它不会将新实体保存到数据库。我需要用我提供的 id 保存新实体。如果我在 db 中提供现有 id - 然后保存成功更新此实体,但如果我设置新 id - 那么什么都没有,甚至没有错误。 我的回购:

import com.xxx.yyy.entities.Game;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface GameRepository extends CrudRepository<Game, Integer> {}

我的实体:

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

import java.util.Objects;

@Table("game_info")
public class Game {

    @Id
    private int id;
    private String name;
    private int wager;

    setters and getters

我的服务:

public void addGame() {

    Game g = new Game();
    g.setId(10);
    g.setName("Name");
    g.saveWager(22);

    gameRepository.save(game);
}

我的桌子:

CREATE TABLE `game_info`
(
    `id`        INT UNSIGNED NOT NULL COMMENT 'Unique identifier of the Game',
    `name`      VARCHAR(32)  NOT NULL COMMENT 'Name of the Game',
    `wager`     INT          NOT NULL COMMENT 'Wager of the Game',
    PRIMARY KEY (`id`),
    UNIQUE (`name`)
);

【问题讨论】:

  • 提供从启动到数据实际持久化期间所有可能的日志。你有一个空的非私人承包商吗?
  • 您使用的是哪个数据库?
  • 我正在使用 MySQL

标签: java mysql spring spring-data


【解决方案1】:

它似乎没有办法用设置的 id 保存实体。我必须像这样编写新的插入方法:

@Modifying
@Query("INSERT INTO `game_info` (`id`, `name`, `wager`) VALUES (:id, :name, :wager)")
void addGame(@Param("id") int id, @Param("name") String name, @Param("wager") Integer wager);

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2021-10-05
    • 2020-04-02
    • 2018-06-05
    • 2021-04-26
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多