Deepesh Shetty
Deepesh Shetty

Reputation: 1166

create one to many relation using jpa(MYSQL)

Hi this is my table structure two tables roles and component.

  +----------------+
    | role           |
    +----------------+
    | role_id : PK |
    | role_name    |
    | role_desc    |
    +----------------+
          |
    +----------------+
    | component      |
    +----------------+
    | comp_id : PK |
    | role_id : FK |
    | parent_comp  |
    | view_per     |
    | add_per      |
    | edit_per     |
    | delete_per   |
    +----------------+

These are bean classes

   package com.example.rolessample;

    public class component {
        private String comp_id;
        private String role_id;
        private String parent_comp;
        private char view_per;
        private char add_per;
        private char edit_per;
        private char delete_per;
    }
package com.example.rolessample;

public class role {

    private String role_id;
    private String role_name;
    private String role_desc;
}

What i need to add to my bean classes?

I have looked in this example but i am not sure how to apply it to my example .

How do you to create a one to many relationship in JPA with no JoinTables?

Thanks in advance .

Upvotes: 1

Views: 646

Answers (2)

shadrus
shadrus

Reputation: 11

Something like this:

 package com.example.rolessample;
    @Entity
    public class component {
        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        private Integer comp_id;
        @ManyToOne
        @JoinColumn(name="role_id")
        private role role_c
        private String parent_comp;
        private char view_per;
        private char add_per;
        private char edit_per;
        private char delete_per;
    }

package com.example.rolessample;
@Entity
public class role {
    @Id
    @GenerValue(strategy = GenerationType.SEQUENCE)
    private Integer role_id;
    private String role_name;
    private String role_desc;
    @OneToMany (mappedBy = "role_c")
    private List <component> component_r
}

Upvotes: 1

Eugene Loy
Eugene Loy

Reputation: 12416

If you do not need the bidirectional relation in your entities - all you need is to change your "role_id" field in "component" class to something like this:

@javax.persistence.ManyToOne
private role role;

Note that in this case "role" will own relation and "component" will be inverse (non-owning) "side".

If you also need bidirectional relation you'll have to add field annotated with @javax.persistence.OneToMany anntoattion with specified "mappedBy" to the "role" class.

Also check out the docs about additional weaks on that annotations to have more control.

Upvotes: 1

Related Questions