JPA @ManyToOne Saving Issue

I have two entity called 'Group' and 'Generic'. When I tried to save Generic data in mySql with the reference of Group it save a new record to group table then use this record in Generic table. How to fix this problem???

Group Entity:

@Entity
@Table(name = "mdcn_group")
public class Group extends BaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
protected Long id;

private String name;
private int status;
private String comments;

public Group() {
}

public Group(long id){
    this.id = id;
}

public Group(long id, String name) {
    this.id = id;
    this.name = name;
}
// ... getter and setter

Generic Entity:

@Entity
@Table(name = "generic")
public class Generic extends BaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
protected Long id;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "group_id")
private Group group;
private String name;
private int status;
private String comments;

public Generic(){}

public Generic(long id){
    this.id = id;
}

public Generic(long id, String name){
    this.id = id;
    this.name = name;
}
// ... getter and setter

Upvotes: 1

Views: 132

Answers (3)

Mr. Taumal
Mr. Taumal

Reputation: 94

I think its your dialect configuration not match with your database. I get this problem sometimes ago.

Go to your application.properties or config file change hibernate dialect "MySQL5Dialect" to "MySQL5InnoDBDialect".

#hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

Upvotes: 2

maruf571
maruf571

Reputation: 1945

Problem in your cascade. Please remove the cascade from your Generic object.

@ManyToOne
@JoinColumn(name = "group_id")
private Group group;

Upvotes: 0

Ram
Ram

Reputation: 1803

I don't see the Generic entity mapped in your Group entity. Please refer here

Please add below mapping in Group entity class and try.

@OneToMany(fetch = FetchType.LAZY, mappedBy = "group")
private List<Generic> generic;

Upvotes: 0

Related Questions