Spring + Hibernate 项目配置(java class版本)
1. 写测试用例
说明:使用spring的原因我可以轻松配置Bean方便进行依赖注入
其中HibernateConfig是bean的配置文件
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=HibernateConfig.class)
public class TestMessage {
@Autowired
private SessionFactory sessionFactory;
@Test
public void test() {
Session session = sessionFactory.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
Message message = new Message("hello world");
Long msgId = (Long)session.save(message);
tx.commit();
session.close();
}
}
2. 在HibernateConfig中实现dataSource和sessionFactory两个bean
其中@ComponentScan具有自动扫描的功能
@Configuration @ComponentScan public class HibernateConfig { @Bean public DataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/shopping"); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUsername("root"); dataSource.setPassword(""); return dataSource; } @Bean public LocalSessionFactoryBean sessionFactory(DataSource dataSource){//自动关联其他的bean:dataSource LocalSessionFactoryBean sfb = new LocalSessionFactoryBean(); sfb.setDataSource(dataSource); sfb.setPackagesToScan(new String[] { "model" }); // sfb.setMappingResources(new String[] { "Spitter.hbm.xml" }); Properties props = new Properties(); props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); props.setProperty("hibernate.hbm2ddl.auto", "update"); props.setProperty("hibernate.show_sql", "true"); sfb.setHibernateProperties(props); return sfb; } }
其中sessoinFactory的入参,dataSource会自被关联到dataSource,进行注入。