2

I have two entities. Sports:

@Entity
public class Sports implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "SPORT_NAME")
    private String name;
...
}

and SportFacility:

@Entity
public class SportFacility implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "SPORTFAC_NAME")
    private String name;
    @OneToMany
    private List<Sports> sports;

....
}

Then I have some created sports in Sports table, for example:

--id-----name-----
- 0  - Football  -   
- 1  - Basketball-
- 2  - Golf      -
------------------

And I need to create sport facility with some sports.Lets take all sports

        List<Sports> listSports = sb.getAllSports(); //JPQL: SELECT s FROM Sports s

        SportFacility sportFacility = new SportFacility("Stadium", listSports);

        em.getTransaction().begin();            
        em.persist(sportFacility);            
        em.getTransaction().commit();  

Error:

java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: database.entities.sports[ id=0 ].

I don' want to use Cascade.ALL or PERSIST becase there are only few sports in table and I always don't need to create new record with same sport... Thank you.

paralen
  • 117
  • 6

2 Answers2

0

The exception is related to the fact that collection of Sports that you retrieved are no longer in the persistence context when you try to persist the SportFacility - persistence context is by default transaction scoped (created when transaction begins and destroyed when it ends) - and EL doesn't know what to do with objects it doesn't control.

Move

em.getTransaction().begin();

to the beginning.

Tomasz Krzyżak
  • 1,087
  • 8
  • 10
0

What does,

sb.getAllSports();

do? Does it use the same EntityManager, or a different one?

database.entities.sports[ id=0 ]

The error seems to indicate that one of your sports has a 0 id, this seems very odd? Did you persist the sports correctly?

James
  • 17,965
  • 11
  • 91
  • 146