【问题标题】:JPA @ManyToOne Saving IssueJPA @ManyToOne 保存问题
【发布时间】:2018-07-22 06:02:11
【问题描述】:

我有两个实体,分别称为“组”和“通用”。当我尝试使用 Group 的引用在 mySql 中保存通用数据时,它将一条新记录保存到组表中,然后在通用表中使用此记录。这个问题怎么解决???

集团实体:

@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

通用实体:

@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

【问题讨论】:

    标签: mysql jpa spring-data-jpa mariadb


    【解决方案1】:

    我没有看到您的 Group 实体中映射的 Generic 实体。请参考here

    请在Group实体类中添加以下映射并尝试。

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

    【讨论】:

    • 我无法从“不起作用”的评论中推断出任何东西。请提供更多详细信息,例如错误、堆栈跟踪、代码等。
    • 它表现得像以前一样。
    【解决方案2】:

    我认为您的方言配置与您的数据库不匹配。我有时会遇到这个问题。

    转到您的application.properties 或配置文件将休眠方言“MySQL5Dialect”更改为“MySQL5InnoDBDialect”。

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

    【讨论】:

    • 您能解释一下为什么org.hibernate.dialect.MySQL5Dialect 不起作用吗?
    • 我不知道为什么org.hibernate.dialect.MySQL5Dialect 不起作用。应该是发动机的问题。 MySQL 中的默认存储引擎是 MyISAM。如果您需要事务和行级锁定,您通常会选择 InnoDB。 see here
    • 我将 mariadb 用于我的 rdbms。 mariadb 建议使用“MySQL5InnoDBDialect”。
    【解决方案3】:

    您的级联问题。请从您的通用对象中删除级联。

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

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2011-10-14
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2019-03-31
      相关资源
      最近更新 更多