1

I'm working with spring mvc and using spring data jpa, and i'm having this error failed to lazily initialize a collection of role could not initialize proxy - no Session i know that this happens because i dont have a open session but i dont know how to keep my session open after i connect to the database this is my code so far:

My jpa config class

@Configuration
@EnableSpringConfigured
@ComponentScan( basePackages = {"com.abc.domain", "com.abc.repository", "com.abc.service","com.abc.authenticate"})
@EnableJpaRepositories(basePackages="com.abc.repository")
public class ConfigJPA 
{

       @Bean
       public LocalContainerEntityManagerFactoryBean entityManagerFactory() 
               throws ClassNotFoundException 
       {

          LocalContainerEntityManagerFactoryBean  em  = 
                  new LocalContainerEntityManagerFactoryBean();

          em.setDataSource( dataSource() );
          em.setPackagesToScan("com.abc.domain");
          em.setPersistenceProviderClass(HibernatePersistence.class);
          em.setJpaProperties( asignarPropiedades() );

          return em;
       }

       //Propiedades Hibernate
       Properties asignarPropiedades() {

           Properties jpaProperties = new Properties();

           jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
           jpaProperties.put("hibernate.format_sql", true);
           jpaProperties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
           jpaProperties.put("hibernate.show_sql", true);

           return jpaProperties;
       }


       @Bean
       public DataSource dataSource(){

          DriverManagerDataSource dataSource = 
                  new DriverManagerDataSource();

          dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");

          //farmatodo22
            dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:XE");
            dataSource.setUsername("DATBASE");
            dataSource.setPassword("mypassword");

          return dataSource;
       }

       @Bean
       public JpaTransactionManager transactionManager() 
               throws ClassNotFoundException 
       {

            JpaTransactionManager transactionManager = 
                    new JpaTransactionManager();

            transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

            return transactionManager;
        }
}

this are my domain classes

User class

@Entity
@Table(name="User")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;


    //**PRIMARY KEY**//

    @Id
    @SequenceGenerator(name="User_id_seq", sequenceName="SEQ_User")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="User_id_seq")
    @Column(name="ID_USER", unique=true, nullable=false, precision=8)
    private Long idUser;




    @ManyToOne
    @JoinColumn(name="id_ldap_server", nullable = false)
    private ServerLdap serverLdap;




    @ManyToMany
    @JoinTable
    (
      name="Usuario_Rol",
      joinColumns = 
      {
        @JoinColumn (name="ID_USER", referencedColumnName="ID_USER")
      },
      inverseJoinColumns = 
      {
        @JoinColumn (name="id_rol", referencedColumnName="id_rol")
      }
    )
    private List<Rol> roles;

This is my role class

    @Entity
    @Table(name="ROL")
    public class Rol implements Serializable 
    {

    private static final long serialVersionUID = 1L;


    //***PRIMARY KEY***///

    @Id
    @SequenceGenerator(name="ROL_ID_GENERATOR", sequenceName="SEQ_ROL")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ROL_ID_GENERATOR")
    @Column(name="id_rol", unique=true, nullable=false, precision=8)
    private Long idRol;




    @ManyToMany(mappedBy="roles")
    private List<User> users;

}

I'm trying to make a ManyToMany realtion between User and Rol, this work nice if i put fetchType = EAGER but i dont want to use that fetch type because i think is not efficient.

stackUser2000
  • 1,485
  • 9
  • 27
  • 53
  • You certainly do not want to make the fetch type EAGER. If you have a significant number of users you could certainly kill your application because a User will certainly need to know their Roles. If Roles also need to know all their Users any user Logging in will result in loading all the Users in the database. – user3360944 Oct 27 '14 at 18:36
  • I have wrote a blog recently about spring-boot, jersey and Data JPA. You might be interested in reading it, http://bit.ly/1vzHYqi – jasenkoh Nov 22 '14 at 19:14

1 Answers1

1

One of the options is to use is Open Session in View but it had few drawbacks and is considered as a bad practice by several people. I would suggest reading the following SO posts to make an informed choice.

Community
  • 1
  • 1
Saket
  • 2,671
  • 3
  • 25
  • 44
  • thanks for the links man, i read the links that you posted and it seems that Open Session in View is a bad practice, so dont you have other links to solve this problem without using Open Session in View Pattern? i thought that Using spring data jpa was going to save me time but it appears that only introduce problems – stackUser2000 Oct 27 '14 at 18:53
  • Another option maybe to use request scoped spring beans which one of articles mentions. I think Spring Data is definitely very useful, you will have to deal with the session issue in any ORM framework you use. – Saket Oct 27 '14 at 18:56
  • i'm going to read with more atention the articles, but is this the easy way to fix this problem because i am new to spring mvc framework and spring jpa data and hibernate, and i forgot to mention that i dont have anything related to sessions or anything with a @transaction annotation in my entire aplication what should i learn first?? – stackUser2000 Oct 27 '14 at 19:32
  • If you are doing it for the first time, I would suggest using OSIV. It is simple to start with and is acceptable most of the times when you have the complete vertical stack of the application in a single JVM. You can always change it later. – Saket Oct 27 '14 at 19:43
  • mmm ok i'm going to try OSIV, but is this going to bring me problems becuase i am doing an application for a company and that application is going to be on a server so users can conect to taht server form their laptops so i dont know if its going to bring me troubles – stackUser2000 Oct 27 '14 at 19:47