Reputation: 105
My entity has field that has one to one connection with another table. How can I set default value for that field. I was trying to to something like this
@Column(columnDefinition = "int default 5")
@OneToOne(cascade = CascadeType.ALL)
private Admin admin;
But I get this error
@Column(s) not allowed on a @OneToOne
Is there a way to achive this without altering table in SQL?
EDIT:
Changed some stuff around. Now I have code like this.
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "admin_id", referencedColumnName = "id", nullable = false, columnDefinition = "bigint(20) DEFAULT 5")
private Admin admin;
I also added @DynamicInsert
and @DynamicUpdate
but it still doesn't work. I also want to note that those Admin objects already exist in DB and I don't want to create them again.
Upvotes: 0
Views: 1837
Reputation: 2790
If one Admin (5) can have many Entities you better use @ManyToOne relationship, which might look like:
@ManyToOne
@JoinColumn(name="ID")
private Admin admin;
And each time you create entity you better fetch from database so you will not get LazyLoadingException, something like this:
Admin admin = adminService.getDefaultAdmin(); //returns 'select a from Admin a where id = 5'
Entity entity = new Entity();
..fill the fields
entity.setAdmin(admin);
entityService.save(entity);
This way you will make sure you have accessed the latest version of admin so you will not override any field of admin or you dont have to worry for cascading.
Upvotes: 1