如何使用.properties在Hibernate中配置和获取会话

时间:2016-03-23 12:59:10

标签: java spring hibernate jpa hibernate-session

我找到的所有示例都包含有关Hibernate.cfg.xml的信息,但我使用的是hibernate.properties而不是它。

在资源文件夹中:

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

我在这里使用属性:

@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);
    }
}

}

是否有机会使用hibernate.properties获取会话(for fetch.LAZY)?

更新

我有JPA,但仍需要会话。

在我的实体中,我有:

 @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;
}

... 

}

所以,当我试图得到:

@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>{
}

如果id_city不为空,我有错误:

enter image description here

如果id_city为空(Fetch.LAZY未使用),一切正常:

enter image description here

0 个答案:

没有答案