Felipe Ramires
Felipe Ramires

Reputation: 1

How insert automatic ManyToMany with OpenJPA

I have 2 classes mapped with OpenJPA. One class is User and has relationship ManyToMany with the AppProfile. In the database I have the table relations USER_APP_PROFILES (ID,User_ID,App_ID).

My class Open JPA User

@Table(name = "USER_PROFILE",schema = "BPMS")
public class UserProfile {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private Integer userID;

    @ManyToMany(mappedBy="listUserProfile", fetch=FetchType.EAGER)
    private List<AppProfile> listAppProfile;
}

My class AppProfile

@Table(name = "APP_PROFILE",schema = "BPMS")
public class AppProfile {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="APP_ID")
    private Integer appID;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
        name="USER_APP_PROFILES",
        joinColumns={@JoinColumn(name="APP_ID", referencedColumnName="APP_ID")},
        inverseJoinColumns={@JoinColumn(name="USER_ID", referencedColumnName="USER_ID")})
        private List<UserProfile> listUserProfile;
     }

I fetch a user into the database by EntitiyManager, after I add the List AppProfile.

Example:

UserProfile userProfile //(populate with fetch in database) 
AppProfile app = new App(); 
app.setAppID(11); 
List<AppProfile> listApp = new ArrayList<AppProfile>(); 
listApp.add(app);
userProfile.setListAppProfile(listApp); 
em.merge(userProfile)

How do I merge, if I need JPA automatic insert in table USER_APP_PROFILES:

User_App_Profile_ID  :  new register
UserID : 1  
AppID : 11

Upvotes: 0

Views: 57

Answers (1)

Try moving the @JoinTable to UserProfile (changing the parameters accordingly) and adding cascade={CascadeType.ALL} to the @ManyToMany annotation.

That should do the trick.

Upvotes: 0

Related Questions