0

All examples that I found contains information about Hibernate.cfg.xml, but I'm using hibernate.properties instead of it.

In resources folder:

hibernate.dialet=org.hibernate.dialect.PostgreSQL9Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

I'm using properties here:

@Configuration
@EnableJpaRepositories("com.some.server.repository")
@EnableTransactionManagement
@PropertySource("classpath:db.properties")
@ComponentScan("com.some.server")

public class DataBaseConfig {

@Resource
private Environment env;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
    em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    em.setJpaProperties(getHibernateProperties());

    return em;
}

@Bean
public DataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(env.getRequiredProperty("db.url"));
    ds.setDriverClassName(env.getRequiredProperty("db.driver"));
    ds.setUsername(env.getRequiredProperty("db.username"));
    ds.setPassword(env.getRequiredProperty("db.password"));

    ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
    ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
    ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
    ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMillis")));
    ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMillis")));
    ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
    ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));

    return ds;
}

@Bean
public PlatformTransactionManager transactionManager() {
    JpaTransactionManager manager = new JpaTransactionManager();
    manager.setEntityManagerFactory(entityManagerFactory().getObject());
    return manager;
}




public Properties getHibernateProperties() {
    try {
        Properties properties = new Properties();
        InputStream is = getClass().getClassLoader().getResourceAsStream("hibernate.properties");
        properties.load(is);

        return properties;
    } catch (IOException e) {
        throw new IllegalArgumentException("Can't find 'hibernate.properties' in classpath!", e);
    }
}

}

Is there any chance to get session (for fetch.LAZY), using hibernate.properties?

UPDATE:

I have JPA, but still need session.

In my entity I have:

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

  ...

@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinColumn(name = "id_city", nullable = true)
private City city;

public City getCity() {
    return city;
}

public void setCity(City city) {
    this.city = city;
}

...

}

AND:

@Entity
@Table(name = "city")
public class City {
 ....

@OneToMany(fetch = FetchType.LAZY, mappedBy = "city")
@JsonIgnore
private Set<User> users;

public Set<User> getUsers() {
    return users;
}

public void setUsers(Set<User> users) {
    this.users = users;
}

... 

}

So, when I try to get:

@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserRepository userRepository;

@Autowired
private ProfessionRepository profRepository;

@RequestMapping(value = "", method = RequestMethod.GET)
public List<User> getAllUsers() {
    //  List<User> list = userRepository.findAll();
    return userRepository.findAll();
}

From:

public interface UserRepository extends JpaRepository<User, Long>{
}

I've got an error, if id_city is not empty:

enter image description here

And if id_city is empty (Fetch.LAZY is not using), everything is ok:

enter image description here

Tom Wally
  • 542
  • 3
  • 8
  • 20
  • I think you need to define the Lazy fetch in entity file rather than in properties file – Lathy Mar 23 '16 at 13:05
  • I have Lazy fetch in entity, but without session I have an error "no session". – Tom Wally Mar 23 '16 at 13:13
  • can you show the code where you are manipulating your entity ? Are you autowiring the EntityManager ? – Olivier Boissé Mar 23 '16 at 13:22
  • decide if you are using JPA API or Hibernate API. In JPA you don't get a "session"; It is EntityManager ... so update your question to clarify what. JPA has no such "hibernate.properties" – Neil Stockton Mar 23 '16 at 13:29
  • Ok, my question was update. – Tom Wally Mar 23 '16 at 13:56
  • @Neil Stockton, why I've got minus? Here is info about hibernate.properties http://www.tutorialspoint.com/hibernate/hibernate_configuration.htm – Tom Wally Mar 23 '16 at 14:03
  • Why you have minus you'd have to ask the person who downvoted it. There is no need for any Hibernate API involvement at all here from what I see, and no thanks I don't need to see some document referring to Hibernates own API to know that. You need an ENTITYMANAGER. Hibernates messages are particularly poor ... you are using JPA so it should say "No EntityManager" not "No Session". – Neil Stockton Mar 23 '16 at 14:06
  • @Neil Stockton Ok, sorry about that. Now I see. – Tom Wally Mar 23 '16 at 14:08
  • 1
    The persistence context is closed after the call of findAll Method. So when the json serialization occurs, it cannot retrieve the city because the persitence context is closed. You can add @JsonIgnore to the city property or if you wan to retrieve the city you need to call getCity() method in the findAll method (or maybe remove the fetch = FetchType.LAZY which is useless) – Olivier Boissé Mar 23 '16 at 14:14
  • @oliv37 please, can you explain how can I call getCity() in findAll(). Because, I really need list of cities in this chain. – Tom Wally Mar 23 '16 at 14:20
  • if you need the city just remove the lazy fetch instruction. When it's lazy the city is not loaded unless you call the getCity method. But if you call getCity on a detached entity (in your controllerà you will get an exception – Olivier Boissé Mar 23 '16 at 14:27
  • @oliv37 Problem is that I already have fetch.Eager in User class (with Profession). I can not use fetch.Eager more than ones in one class, cause I will get an exception. I have to use fetch.Lazy – Tom Wally Mar 23 '16 at 14:32
  • You can use fetch.Eager more than ones – Olivier Boissé Mar 23 '16 at 14:33

0 Answers0