JPA无法将Long字段设置为Long

时间:2017-01-25 15:45:47

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

我想我在某个地方犯了一个错误...... 它假设1名球员有1个统计表(oneToOne)

班主任:

@helper DateFormatter(object date)
{
    var shortDateLocalFormat = "";
    if (date != null) {
       shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
    }

    @shortDateLocalFormat
}

班级统计:

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

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

如果我这样做,那很好:

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

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

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

我认为我的oneToOne参考可能有问题。

2 个答案:

答案 0 :(得分:1)

  

如果我删除了参考号。从stats到uid @JoinColumn(name =&#34; player_uid&#34 ;, referencedColumnName =&#34; uid&#34;),一切运作良好。

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

11.1.25 JoinColumn Annotation

...

  

如果缺少referencedColumnName元素,则假定外键引用引用表的主键。

     

支持不是引用表的主键列的引用列是可选的。使用此类映射的应用程序将无法移植。

因此您应该将注释更改为:

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

或删除referencedColumnName,因为提供商将使用默认主键(在这种情况下为id)。

答案 1 :(得分:0)

我认为你需要在这里实施PlayerDAO。你可以试试这样的东西

@Repository    
public interface JPAPlayerDAOImpl extends JPAPlayerDAO, JpaRepository<Player, Long> {

    @Override
    @Query("SELECT player FROM Player player WHERE player.uid =:uid")
    Player findByUid(@Param("uid") Long uid);

    @Override
    @Query("SELECT player FROM Player player WHERE player.name =:name")
    Player findByName(@Param("name") String name);
}

PlayerDAO会是这样的:

public interface JPAPlayerDAO {
   Player findByUid(Long uid);
   Player findByName(String name);
}