Search code examples
jpajakarta-eeglassfisheclipselinkentitymanager

What can be a reason for persist()/merge() to create two rows in database?


I am starting my second project in JavaEE and created simple singleton bean to init some data in database for future debug purposes. However, I am stuck at strange problem - persist method(as well as merge) creates two rows in database. And all I do is this:

@Singleton   //ejb singleton
@Startup
public class DatabaseInitializer {

  @PersistenceContext
  private EntityManager entityManager;

  @PostConstruct
  public void initDatabase() {
    Calendar releaseDate = Calendar.getInstance();
    releaseDate.set(2010, 6, 16);
    Movie movie;
    List<Genre> genres = Arrays.asList(Genre.ACTION, Genre.ADVENTURE, Genre.MYSTERY, Genre.SCIFI, Genre.THRILLER);
    movie = new Movie("inception-2010", "Inception",
            "long string", releaseDate, "http://inceptionmovie.warnerbros.com/", genres);

    entityManager.persist(movie);
  }
}

And this is how Movie entity looks like:

@Entity
public class Movie {
  @Id
  @TableGenerator(name = "MovieSeq")
  @GeneratedValue(strategy = GenerationType.TABLE, generator = "MovieSeq")
  private int id;

  // @Column(unique = true) //couses exception due to creaton of two rows
  private String uniqueName;

  private String title;

  @Column(length = 1024)
  private String overview;

  @Temporal(TemporalType.DATE)
  private Calendar releaseDate;

  private String homepage;

  @ElementCollection   //tried removing this property, doesn't matter, 
  private List<Genre> genres;   //simple list of emuns

  //constructors, getters/setters
  ...
}

I tried googling this problem but it seems to happen if people mess up their relationships in JPA, but as we can see this is simplest case ever. Of course if I create 10 movies then JPA creates 20 rows and so on.

I am using Glassfish(Payara) which uses EclipseLink as JPA provider and Oracle 11g is my database if it matters at all. I have no idea how to fix this, because I don't have any idea of potential problems with my design.


Solution

  • As Dragan Bozanovic suggested problem is coused by @PostConstruct method called twice. I am still working on fixing that, but it's topic for another question