我在 Netbeans 7.0 上使用 EclipseLink (JPA 2.0) 和 MySQL 数据库 - 我根据 this screencast 配置该数据库。但有时,当我持久化一个对象/实体时,我的表会在该对象持久化之前被清除,并且我会得到一个仅包含该对象的表(就像它已被清除一样)。我只是简单地在数据库中添加新条目(填充)。
如何防止这种情况发生?
这是我的代码:
Movie movie = new Movie(
jsondata.path("Title").getTextValue(),
jsondata.path("Year").getValueAsInt(),
jsondata.path("Genre").getTextValue(),
jsondata.path("Plot").getTextValue(),
jsondata.path("Poster").getTextValue());
persist(movie);
我的 persist() 函数:
public static void persist(Object object) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("AllmoviesPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(object);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
}
em.close();
}
我的电影对象/实体:
@Entity
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@Column(name="MOVIEYEAR")
private int year;
private String genre;
private String synopsis;
private String image;
public Movie(String title, int year, String genre, String synopsis, String image) {
this.title = title;
this.year = year;
this.genre = genre;
this.synopsis = synopsis;
this.image = image;
}
public Movie() {
}
/* ... Getters and Setters stuff ... */
}
我的 persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="AllmoviesPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>allmovies.data.Movie</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://123.123.123.123:3306/psanta_allmovies"/>
<property name="javax.persistence.jdbc.password" value="XXXXXX"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="psanta_allmovies"/>
</properties>
</persistence-unit>
</persistence>
最佳答案
尝试将日志记录打开为 FINEST 或 FINE 以查看发生了什么。 (“eclipselink.logging.level”=“最好的”)。
EclipseLink 确实有一个在启动时重新创建表的选项(“eclipselink.ddl- Generation”=“drop-and-create-tables”),请确保您没有使用它。 NetBeans 或 Glassfish 可能会默认设置此设置,我认为他们可能会在开发模式下执行此操作。
关于java - 如何防止 EclipseLink (JPA 2.0) 清除我的数据库/表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6048019/