java - JPA 无法将 Long 字段设置为 Long

标签 java hibernate spring-boot spring-data-jpa

我想我在某个地方犯了错误......
假设 1 名玩家有 1 个统计表 (oneToOne)

类(class)玩家:

@Component
@Entity
@Table(name = "player")
public class Player {

    @Id
    @GeneratedValue
    @JsonView(View.Summary.class)
    @Column(name = "id")
    private Long id;

    @Column(name = "uid", unique = true, nullable = false)
    @JsonView(View.Summary.class)
    private Long uid;

    @OneToOne(mappedBy = "player", cascade = CascadeType.ALL)
    @JsonView(View.Summary.class)
    private Stats stats;
    ....

类(class)统计:

@Component
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "stats")
public class Stats implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    @JsonView(View.Summary.class)
    @Column(name = "id")
    private Long id;

    @OneToOne
    @JoinColumn(name = "player_uid", referencedColumnName = "uid", nullable = false)
    @JsonView(View.Summary.class)
    private Player player;
    ....

PlayerDAO 类:

public interface JPAPlayerDAO extends JpaRepository<Player, Long> {
    Player findByUid(Long uid);
    Player findByName(String name);
}

如果我这样做,那就没问题了:

Player p = new Player();
p.setUid(123L);
p.setName("Mike");
updater.saveOrUpdatePlayer(p);
p = playerDAO.findOne()

如果我尝试通过名称或 uid 查找它,则会收到错误:

Player p = new Player();
p.setUid(123L);
p.setName("Mike");
updater.saveOrUpdatePlayer(p);
p = playerDAO.findByName("Mike")
or
p = playerDAO.findByUid(123L)
....
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field...
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field ...entities.Player.uid to java.lang.Long

我认为我的 oneToOne 引用可能有问题。

最佳答案

If I remove a ref. from stats to uid @JoinColumn (name = "player_uid", referencedColumnName = "uid"), all works well.

如果是这种情况,问题可能出在您已经提到的关联上。 根据JPA规范,对非主键映射的支持是可选的,这意味着必须不支持:

11.1.25 JoinColumn注解

...

If the referencedColumnName element is missing, the foreign key is assumed to refer to the primary key of the referenced table.

Support for referenced columns that are not primary key columns of the referenced table is optional. Applications that use such mappings will not be portable.

所以你应该将注释更改为:

@JoinColumn(name = "player_uid", referencedColumnName = "id")

或删除referencedColumnName,因为提供程序将使用默认值,即主键(在本例中为id)。

关于java - JPA 无法将 Long 字段设置为 Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41855802/

相关文章:

java - 使用 Java 将图像上传到 PostgreSQL

java - 调试 AngularJS + Spring MVC + Tomcat Web 应用程序

java - Springboot UnsatisfiedDependencyException?

java - Spring Boot - NoClassDefFoundError NioBlockingSelector$BlockPoller

java - 仅当通过 Eclipse : POST on Spring Boot Controller fails with HTTP Error 415 运行时

java - 需要不兼容的类型

java - 在方法中模拟新对象的创建

java - @Transactional 注释未启动事务(Guice Persist)

java - 如何在 JPA 中创建成对列表作为参数?

oracle - hibernate 重复查询