JPA,提交时没有向数据库添加任何内容

JPA, nothing is added to Database when commit

我有两个表(command 和 commandLine),我想在插入新命令时同时写入两个表 这是我的命令对象,我使用 OneToMany 来映射对象 CommandLine

@Entity
@Table(name = "t_commands")
public class Command {

    @Id @Getter
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idCommand;

    @Getter @Setter
    @ManyToOne(targetEntity = User.class)
    @JoinColumn(name = "idUser", nullable = false)
    private User user;

    @Getter @Setter
    @Column(name = "commandDate")
    private String date;

    @Getter @Setter
    @OneToMany(targetEntity = CommandLine.class, mappedBy = "idCommand")
    private List<CommandLine> lines = new ArrayList<>();

    public Command(User user, String date) {
        this.user = user;
        this.date = date;
    }

    public Command() {
    }

和我的 CommandLine 对象,我使用 ManyToOne 映射对象 Command

@Entity
@Table(name = "t_commandlines")
public class CommandLine {

    @Id @Getter
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idCommandLine;

    @Getter
    @ManyToOne(targetEntity = Command.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "idCommand", nullable = false)
    private Command idCommand;

    @Getter @Setter
    @ManyToOne(targetEntity = Article.class)
    @JoinColumn(name = "idArticle", nullable = false)
    private Article article;

    @Getter @Setter
    private int quantity;


    public CommandLine(Article article, int quantity) {
        this.article = article;
        this.quantity = quantity;
    }

和我的 CommandDAO

public class CommandDAO implements IDao<Command> {

    @Override
    public boolean create(Command object) {
        connect().persist(object);
        return true;
    }
}

我用界面

public interface IDao<T> {

    default EntityManager connect() {
        EntityManagerFactory entityManagerFactory;
        EntityManager entityManager;

        entityManagerFactory = Persistence.createEntityManagerFactory("webstore");
        entityManager = entityManagerFactory.createEntityManager();

        return entityManager;
    }

    default T read(Long id){return null;}
    default List<T> getAll() {return null;}
    default boolean create(T object) {return false;}
    default boolean update(T object) {return false;}
    default boolean delete(T object) {return false;}
    default Long getCount() {return 1L;}
}

我没有错误,但我的数据库中没有写入任何内容,我可以用这种结构从数据库中检索数据,但无法写入

它没有应用更改,因为没有事务,所以持久化操作没有刷新到数据库。

这里是代码的简化示例:

public class CommandDAO implements IDao<Command> {

    @Override
    public boolean create(Command object) {
        EntityManager em = connect();
        try {
          em.getTransaction().begin();
          em.persist(object);
          em.getTransaction().commit();
          return true;
        }
        finally {
          em.close();
        }
    }
}

此外,没有理由在每次调用 connect() 时都创建 EntityManagerFactory。工厂的创建比较繁重但是工厂是线程安全的,你可以在需要的时候复用它。 每次需要时创建一个 EntityManager 是有意义的,但是当你用完它时你必须关闭它。