博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Kiss MySQL goodbye for development and say hello to HSQLDB
阅读量:4442 次
发布时间:2019-06-07

本文共 5978 字,大约阅读时间需要 19 分钟。

The days of using MySQL, DB2, PostgreSQL etc for development is  over.. I don’t know why any programmer would be developing using them..

Every deveroper should be running some in memory database like HSQLDB as part of the project for development and testing then move the a full size database for unit testing, staging and production.

This is a sample Spring Project to show how to use JavaConfig and  HSQLDB. This example also will show how to use @PropertySource for  reading properties and using the Environment Object to add properties to your objects.

How to use Spring JavaConfig and not XML files for configuation

Consider replacing Spring XML configuration with JavaConfig

Using Spring XML configuration is so 2000’s the time has come to push the XML away and look at JavaConfig.

Here is the main code to my sample project

 
01.
public class Main
02.
{
03.
 
04.
    private static final Logger LOGGER = getLogger(Main.class);
05.
 
06.
    public static void main(String[] args)
07.
    {
08.
        // in this setup, both the main(String[]) method and the JUnit method both specify that
09.
        ApplicationContext context = new AnnotationConfigApplicationContext( DatabaseConfiguration.class );
10.
 
11.
        MessageService mService = context.getBean(MessageService.class);
12.
 
13.
        /**
14.
         *   Saving Message to database
15.
         */
16.
        Message message = new Message();
17.
        message.setMessage("Hello World");
18.
        mService.SaveMessage(message);
19.
        /**
20.
         * Saving 2nd Message in database.
21.
         */
22.
        message.setMessage("I love NYC");
23.
        mService.SaveMessage(message);
24.
 
25.
        /**
26.
         * Getting messages from database
27.
         *    - display number of message(s)
28.
         *    - display each message in database
29.
         */
30.
        List<Message> myList = mService.listMessages();
31.
        LOGGER.debug("You Have " + myList.size() + " Message(s) In The Database");
32.
 
33.
        for (Message i : myList)
34.
        {
35.
            LOGGER.debug("Message: ID: " + i.getId() + ", Message: " + i.getMessage() + ".");
36.
        }
37.
    }
38.
}
 

Now lets take a look at how I setup the database in JavaConfig and not in a XML file.

 
01.
@Configuration
02.
@EnableTransactionManagement
03.
@ComponentScan(basePackageClasses = {Main.class})
04.
@PropertySource("classpath:application.properties")
05.
public class DatabaseConfiguration
06.
{
07.
@Bean
08.
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
09.
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
10.
    resourceDatabasePopulator.addScript(new ClassPathResource("/schema.sql"));
11.
 
12.
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
13.
        dataSourceInitializer.setDataSource(dataSource);
14.
        dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
15.
        return dataSourceInitializer;
16.
    }
17.
 
18.
    @Bean
19.
    public DataSource hsqlDataSource() {
20.
        BasicDataSource basicDataSource = new BasicDataSource();
21.
        basicDataSource.setDriverClassName(org.hsqldb.jdbcDriver.class.getName());
22.
        basicDataSource.setUsername("sa");
23.
        basicDataSource.setPassword("");
24.
        basicDataSource.setUrl("jdbc:hsqldb:mem:mydb");
25.
        return basicDataSource;
26.
    }
27.
 
28.
    @Bean
29.
    public LocalSessionFactoryBean sessionFactory(Environment environment,
30.
                                              DataSource dataSource) {
31.
 
32.
        String packageOfModelBeans = Message.class.getPackage().getName();
33.
        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
34.
        factoryBean.setDataSource(dataSource);
35.
        factoryBean.setHibernateProperties(buildHibernateProperties(environment));
36.
        factoryBean.setPackagesToScan(packageOfModelBeans);
37.
        return factoryBean;
38.
    }
39.
 
40.
    protected Properties buildHibernateProperties(Environment env) {
41.
        Properties hibernateProperties = new Properties();
42.
 
43.
        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
44.
        hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
45.
        hibernateProperties.setProperty("hibernate.use_sql_comments", env.getProperty("hibernate.use_sql_comments"));
46.
        hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
47.
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
48.
 
49.
        hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
50.
 
51.
        hibernateProperties.setProperty("javax.persistence.validation.mode", env.getProperty("javax.persistence.validation.mode"));
52.
 
53.
        //Audit History flags
54.
        hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", env.getProperty("org.hibernate.envers.store_data_at_delete"));
55.
        hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", env.getProperty("org.hibernate.envers.global_with_modified_flag"));
56.
 
57.
        return hibernateProperties;
58.
    }
59.
 
60.
    @Bean
61.
    public HibernateTransactionManager hibernateTransactionManager(SessionFactory sessionFactory) {
62.
        return new HibernateTransactionManager(sessionFactory);
63.
    }
64.
}
 

You can see how easy it is to use JavaConfig and Not XML.. The time of using XML files with Springs is over…

Down and Run Project

If you would like to download the project from GitHub and run it just follow the following commands:

 
1.
git clone git@github.com:JohnathanMarkSmith/NoMySQL.git
2.
cd NoMySQL
3.
mvn package
4.
cd target
5.
java -jar NoMySQL.jar
 

Thats it and you should see the following line on the console:

2013-04-30 10:47:17,790 [main] DEBUG com.johnathanmarksmith.noMySQL.Main - You Have 2 Message(s) In The Database2013-04-30 10:47:17,790 [main] DEBUG com.johnathanmarksmith.noMySQL.Main - Message: ID: 1, Message: Hello World.2013-04-30 10:47:17,790 [main] DEBUG com.johnathanmarksmith.noMySQL.Main - Message: ID: 2, Message: I love NYC.

This Project is using Java, Spring, Hibernate, Maven, jUnit, Log4J, HSQLDB and Github.

LIFE IS SO EASY WORKING WITH GIT, MAVEN, SPRING….

转载于:https://www.cnblogs.com/mybi/p/4179895.html

你可能感兴趣的文章
跟我一起读postgresql源码(六)——Executor(查询执行模块之——查询执行策略)
查看>>
scala的4中for循环,及while和do while循环
查看>>
vue.js windows下开发环境搭建
查看>>
数据表改变之后数据的迁移
查看>>
雷林鹏分享:Ruby 环境变量
查看>>
掉书袋的东东,我喜欢。。。
查看>>
通过MYSQL命令行直接建数据库
查看>>
safari 插件安装之alipay
查看>>
【语言处理与Python】3.3使用Unicode进行文字处理
查看>>
python+senium+chrome的简单爬虫脚本
查看>>
CoronaSDK场景管理库:Composer library (上)
查看>>
Go语言程序结构
查看>>
【算法导论】第6章堆排序及利用堆建立最小优先级队列
查看>>
Log4Net配置方法
查看>>
ASP.NET禁用一部分验证控件,ValidationGroup的设置与使用
查看>>
JavaScript DOM高级程序设计 5动态修改样式和层叠样式表2--我要坚持到底!
查看>>
[.NET源码学习]实例化Font,遭遇字体不存在的情况。
查看>>
手机如何设置静态IP
查看>>
JS操作文件
查看>>
解放创意——自由人的自由联合
查看>>