【问题标题】:Java JPA - Persisting @OneToMany entityJava JPA - 持久化@OneToMany 实体
【发布时间】:2016-01-21 01:59:08
【问题描述】:

大家好,

这些天我遇到了@OneToMany 持久对象的问题。有问题的地方是我正在尝试创建两个对象(一个是 OneToMany,另一个是 ManyToOne),我想持久化 @OneToMany 一个,并自动将 @ManyToOne 持久化到数据库中。 (所有表都设置为自增,Collection 在 Komponenta.class 的构造函数中初始化,我只放了与这个问题相关的部分)。这是我的代码:

public class Komponenta implements Serializable {

@Id
private Integer idKom;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "idKom")
private Collection<Ima> imaCollection = new ArrayList<>();

}

public class Ima implements Serializable {

@Id
private Integer idIma;

@JoinColumn(name = "idKom", referencedColumnName = "idKom")
@ManyToOne
private Komponenta idKom;

}

    // runnable part
    Tools.em.getTransaction().begin();

    Komponenta k = new Komponenta();
    Ima i = new Ima();

    Collection<Ima> list = k.getImaCollection();
    list.add(i);
    k.setImaCollection(list);      

    i.setIdKom(k);

    Tools.em.persist(k);
    Tools.em.getTransaction().commit();

我从控制台输出收到此类错误:

内部异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列“idKom”不能为空 错误代码:1048

【问题讨论】:

  • 你不认为 id 不应该为空吗?您没有为“idKom”设置任何值

标签: java database jpa runtime-error


【解决方案1】:

要使用 MySQL AUTO_INCREMENT 列,您应该使用 IDENTITY 策略:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idKom;

在 MySQL 中使用 AUTO 会得到什么:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer idKom;

实际上相当于

@Id @GeneratedValue
private Integer idKom;

【讨论】:

  • AUTO 实际上意味着由 JPA 提供者来做它想做的事,不一定在 MySQL 上使用 AUTOINCREMENT。 IDENTITY 选项是实现可靠行为的方式
  • 非常感谢!我所需要的就是将 GeneratedValue 注释与私有 Integer idKom 的 Id 一起放置。这解决了我的问题。附:任何人都知道为什么 mySql 在使用自动增量设置惰性进入表 Komponenta 时,它会放置 ID:1、51、101、151...?
  • 试试@GeneratedValue(strategy=GenerationType.SEQUENCE)
【解决方案2】:

您将值设置为idKomKomponenta 实例。

让id自动生成

@Id
@GeneratedValue(strategy=GenerationType.AUTO)//Use strategy accoringly
private Integer idKom;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多