1
<prop key="hibernate.hbm2ddl.auto">create</prop>
創建一個新的數據庫模式並創建<prop key="hibernate.hbm2ddl.auto">update</prop>
如果它不存在並更新現有的數據庫模式。如果我想檢查數據庫模式是否存在,並根據將創建的數據庫模式,我該如何實現這一點。目前我applicationContext.xml
的配置是:Hibernate自定義模式創建
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>info.ems.models.User</value>
<value>info.ems.models.Role</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="dao" class="info.ems.hibernate.HibernateEMSDao" init-method="createSchema">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
而且HibernateEMSDao.java:
public class HibernateEMSDao implements EMSDao {
private final Logger logger = LoggerFactory.getLogger(getClass());
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public void saveUser(User user) {
hibernateTemplate.saveOrUpdate(user);
}
public List<User> listUser() {
return hibernateTemplate.find("from User");
}
public void createSchema() {
logger.info("inserting default admin user into database");
User admin = new User();
admin.setUsername("admin");
admin.setName("Admin");
admin.setEmail("admin");
admin.setPassword("21232f297a57a5a743894a0e4a801fc3");
saveUser(admin);
logger.info("Admin inserted into database");
try {
System.out.println(listUser().get(0).getId());
} catch (Exception e) {
logger.error("===================Error================");
}
}
}
這是工作。什麼配置會幫助我獲得這個? 喜歡的東西:
- 檢查的用戶使用id = 1存在
- 如果沒有創建模式
感謝和問候。