当我们通过java而不是xml配置文件进行配置时,我们如何映射hibernate表资源 - 感谢帮助。
hibernate资源的xml-mapping:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>/config/Stock.hbm.xml</value>
</list>
</property>
</bean>
Java的映射?
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-sql.properties" })
@ComponentScan({......."})
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] {...... });
sessionFactory.setHibernateProperties(hibernateProperties());
(HOW DO WE INTRODUCE mappingResources HERE?)
return sessionFactory;
}
答案 0 :(得分:0)
您可以在运行时编辑您的配置,如下所示:
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
或类似这样的课程:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
答案 1 :(得分:0)
以下是您感兴趣的最小工作Hibernate + JPA设置:
@Configuration
@EnableTransactionManagement
public class DaoConfiguration {
@Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.setProperty(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
properties.setProperty(Environment.DRIVER, "org.hsqldb.jdbcDriver");
properties.setProperty(Environment.URL, "jdbc:hsqldb:mem:testdb");
properties.setProperty(Environment.USER, "sa");
properties.setProperty(Environment.PASS, "");
properties.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "org.springframework.orm.hibernate4.SpringSessionContext");
properties.setProperty(Environment.STATEMENT_BATCH_SIZE, "30");
properties.setProperty(Environment.SHOW_SQL, "true");
properties.setProperty(Environment.HBM2DDL_AUTO, "update");
return properties;
}
@Bean
public HibernateEntityManagerFactory entityManagerFactory() {
Ejb3Configuration config = new Ejb3Configuration();
return (HibernateEntityManagerFactory) config.addProperties(hibernateProperties()).
addAnnotatedClass(User.class).
buildEntityManagerFactory();
}
@Bean
public SessionFactory sessionFactory() {
return entityManagerFactory().getSessionFactory();
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
}
答案 2 :(得分:0)
模型对象上的@Entity解决了这个问题。 xml配置选项不需要此注释。