2

I have scala trait as follows

trait Id {
            @javax.persistence.Id
            @GeneratedValue(strategy=GenerationType.IDENTITY)
            @BeanProperty
            var id: Long = _
}

Now I have an entity (Person) that I want to extend the Id trait but change the id column name to personid. How can I achieve this?
Person Snippet Below:

@NamedQuery(name=”findAll”,query=”select p from Person p”)
class Person extends Id {
    @BeanProperty
    @Column(name=”personid”)
    def personid = id
}

2 Answers 2

5

You can introduce a method personid which returns the value of id:

trait Person extends Id {
  def personid = id
}

Removing the id member in Person would violate the principle that subclasses instances must always be usable as if they were instance of the base class. That is, if Person extends Id, then you must be able to call all the methods of id on it, otherwise you would not be able to assign an object of type Person to a reference of type Id.

So, if you extend Id, the extended trait/class will always have id.

You can, however, restrict the visibility of id in the base trait Id by making id package-private:

private[package_name] var id: Long = _
Sign up to request clarification or add additional context in comments.

2 Comments

Now the insert works but when I tried to load the Entity list I get an error: Unknown column ‘person0_.id’ in ‘field list’.
Can you edit your post with the complete concise snippet that you are executing?
2

If what you want to do is to simply override the column name used by JPA to then you should be able to use the AttributeOverride annotation.

It might look something like:

@MappedSuperclass
trait Id {
        @javax.persistence.Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @BeanProperty
        var id: Long = _
}

@Entity
@AttributeOverride(name="id", column=@Column(name="personid"))
class Person extends Id

If you want to change the property name used to access id then you could do something like Alex is suggesting...

Edit: Forgot to let the Person entity extend the Id trait

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.