Hibernate自定义模式创建 [英] Hibernate custom schema creation

查看:92
本文介绍了Hibernate自定义模式创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< prop key =hibernate.hbm2ddl.auto> create< / prop> 创建一个新的数据库模式,< prop key =hibernate.hbm2ddl.auto>更新< / prop> 如果它不存在,则创建并更新现有的数据库模式。如果我想检查数据库模式是否存在,并根据将创建的数据库模式,我该如何实现这一点。目前,我的 applicationContext.xml 的配置是:

 < bean id =sessionFactoryclass =org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean> 
< property name =dataSourceref =dataSource/>
< property name =annotatedClasses>
< list>
< value> info.ems.models.User< / value>
<值> info.ems.models.Role< /值>
< / list>
< / property>
< property name =hibernateProperties>
<道具>
< prop key =hibernate.dialect> org.hibernate.dialect.HSQLDialect< / prop>
< prop key =hibernate.show_sql> true< / prop>
< prop key =hibernate.hbm2ddl.auto>建立< / prop>
< /道具>
< / property>
< / bean>
< bean id =daoclass =info.ems.hibernate.HibernateEMSDaoinit-method =createSchema>
< property name =sessionFactoryref =sessionFactory/>
< / bean>

和HibernateEMSDao.java:

 public class HibernateEMSDao implements EMSDao {

private final Logger logger = LoggerFactory.getLogger(getClass());

私有HibernateTemplate hibernateTemplate;

public void setSessionFactory(SessionFactory sessionFactory){
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}

public void saveUser(User user){
hibernateTemplate.saveOrUpdate(user);
}

公共列表<用户> listUser(){
return hibernateTemplate.find(from User);


public void createSchema(){
logger.info(将缺省管理用户插入数据库);
User admin = new User();
admin.setUsername(admin);
admin.setName(Admin);
admin.setEmail(admin);
admin.setPassword(21232f297a57a5a743894a0e4a801fc3);
saveUser(admin);
logger.info(管理员插入数据库);

尝试{
System.out.println(listUser()。get(0).getId());
} catch(Exception e){
logger.error(===================错误========== ==);
}
}
}

它正在工作。什么配置会帮助我获得这个?
类似于:


  • 检查ID为1的用户是否存在

  • 如果不是创建模式



感谢和问候。

解决方案<您可以禁用 hibernate.hbm2ddl.auto 选项,检查条件(可能使用普通JDBC)并调用(或不要) create SchemaExport 的方法>类。这可以在您的应用程序的初始化代码中完成(如果您使用的是Web应用程序,则可以使用 ServletContextListener )。



一个关于如何使用 SchemaExport 类的例子:

  AnnotationConfiguration config = new AnnotationConfiguration(); 
config.addAnnotatedClass(info.ems.models.User.class);
config.addAnnotatedClass(info.ems.models.Role.class);
config.configure();
新的SchemaExport(config).create(true,true);


<prop key="hibernate.hbm2ddl.auto">create</prop> creates a new database schema and <prop key="hibernate.hbm2ddl.auto">update</prop> create if it is not exists and update existing database schema. If I want to check whether database schema exists or not and depending on that a database schema will be created, how can I achieve this. Currently the configuration of my applicationContext.xml is:

<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>  

And the 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================");
        }
    }               
}

It is working. What configuration will help me to gain this? Something like:

  • Check an user with id=1 exists
  • If not create the schema

Thanks and regards.

解决方案

You could disable the hibernate.hbm2ddl.auto option, check the conditions (probably using plain JDBC) and call (or don't) the create method of the SchemaExport class. This would be done in your application's initialization code (a ServletContextListener in case you are working with a web app).

An example on how to use the SchemaExport class:

AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(info.ems.models.User.class);
config.addAnnotatedClass(info.ems.models.Role.class);
config.configure();
new SchemaExport(config).create(true, true);

这篇关于Hibernate自定义模式创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆