在JPA中使用手动创建的表

时间:2018-07-16 16:19:53

标签: jpa jpa-2.0

我已经通过SQL手动创建了表。

    CREATE TABLE author(
author_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
author_phone_fk INT NULL,
CONSTRAINT  `author_phone_fk`
FOREIGN KEY(author_phone_fk) REFERENCES phone(phone_id));

CREATE TABLE phone(
phone_id INT AUTO_INCREMENT PRIMARY KEY,
number VARCHAR(20));

我上课了

@Entity
public class Phone {

    @Id
    @Column(name = "phone_id")
    private int id;

    private String number;

  }

@Entity
public class Author {

    @Id
    @Column(name = "author_id")
    private int id;

    private String name;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "author_phone_fk")
    private Phone phone;
}

在保存Author对象时,我有例外

  

无法添加或更新子行:外键约束失败   ({final_projectauthor,约束author_phone_fk外键   ({author_phone_fk)参考文献phonephone_id))

我不知道如何解决该错误。 Tnx

测试数据:

 EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");

        EntityManager em = emf.createEntityManager();

        EntityTransaction transaction = em.getTransaction();

        transaction.begin();

        Phone myPhone = new Phone("89198130228");

        Author myAuthor = new Author("Alex", myPhone);

        em.persist(myAuthor);

        transaction.commit();

        em.close();

Stacktrace:

  

休眠:插入电话(数字,phone_id)值(?,?)   休眠:插入作者(名称,author_phone_fk,author_id)   值(?,?,?)线程“ main”中的异常   javax.persistence.RollbackException:提交错误   交易于   org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:77)     在   org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71)     在domain.TestAdvert.main(TestAdvert.java:44)上,由以下原因引起:   javax.persistence.PersistenceException:   org.hibernate.exception.ConstraintViolationException:无法   执行语句的原因:   com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   无法添加或更新子行:外键约束失败   ({final_projectauthor,约束author_phone_fk外键   ({author_phone_fk)参考文献phonephone_id))

0 个答案:

没有答案