Default value for column as entity


#1

BaseEntity

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

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Min(5)
    @Max(25)
    @Column(name = "name", nullable = false)
    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "rank_id",)
    private Rank rank;
}

RankEntity:

@Entity
@Table(name = "rank")
public class Rank {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Column(name = "name", nullable = false, updatable = false)
    private String name;

    @Column(name = "permissions")
    @ElementCollection
    private Set<String> permissions = new HashSet<>();
}

In Player entity exists column rank. How do I specify a default value for it so that it gets the rank entity when it is initialized?


#2

How do I specify a default value for it so that it gets the rank entity when it is initialized?

That’s a Foreign Key. What default value should a Foreign Key column contain?


#3

Property rank in Player entity should take default Rank from database.
Default rank it is rank with name “default”.
How do I point this in the ForeignKey?


#4

If you want to do that, you need to use the Hibernate-specific @JoinFormula. Check out this article for an example.


#5

Okay. However if i’ll set a other rank to Player entity session.find(Player.class, id) will return me entity with new rank or it will be use JoinFormula and return default rank?


#6

Nope.If you’re asking this question it means you are better off replacing the association with a query.