I currently have a table which looks like this:
Users
username
address
dob
…
And
Roles
username
role
I want to make a foreign key constraint between Role.username and User.username. How should I go about doing this with ann
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Would be good if you could drop the “s” from the end of your table/type names – each row/instance represents one item, not many.
Use
@ManyToOneannotated field within Role entity – with field of type “User” and name “user”. This is a relationship field that is owned by Role – the FK column will go in Role table.Optionally, use
@OneToMany(mappedBy="user")annotation field within User entity – with field of typeCollection<Role>orList<Role>, dependending on whether you want to preserve the ordering of app insertion when you write to DB. This is a non-owned relationship field, meaning no FK column will go into User table – we must usemappedByto name the owned relationship on the User entity. However, if you omit (2) and include (3) this becomes owned, and then mappedBy is not used, but column=”some_db_colname” could be used instead.In User entity set
@Idon username (single PK field of basic type).In Role entity set
@Idon both user (non-basic type) and also role (basic type).Additionally, because you have two
@Idfields and because one of them is not a basic type, you must additionally create aRoleIdclass that repeats the same field names, but this time, maps the data types to the underlying basic types – as found in the PK field of the referenced entities and as consistent with underlying DB table. Annotate Role with@IdClass(RoleId)Ready to use… =:-)