简体   繁体   English

如何检查h2嵌入式数据库是否已创建?

[英]How to check that h2 embedded database is created?

I have app-context file with embedded database: 我有带有嵌入式数据库的应用程序上下文文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <jdbc:embedded-database id="dataSource" type="H2">
        <jdbc:script location="classpath:META-INF/schema.sql" />
        <jdbc:script location="classpath:META-INF/data.sql" />
    </jdbc:embedded-database>

    <bean id="reportDao" 
          class="jdbc.dao.ImplReportDao"
          p:dataSource-ref="dataSource" />

</beans>

And I have the following src/META-INF/schema.sql file: 而且我有以下src / META-INF / schema.sql文件:

USE `reports`;

/*Table structure for table `reports` */

DROP TABLE IF EXISTS `reports`;

CREATE TABLE `reports` (
  `id` int(9) unsigned zerofill NOT NULL,
  `parent_id` int(9) unsigned zerofill NOT NULL DEFAULT '0000',
  `name` varchar(99) NOT NULL,
  `is_category` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;

and src/META-INF/data.sql file: src / META-INF / data.sql文件:

insert  into `reports`.`reports`(`id`,`parent_id`,`name`,`is_category`) 
values 
(0000,0000,'Reports',1),
(0001,0000,'Card emission',1),
(0002,0000,'Technical reports',1);

And ImplReportDao looks like this: ImplReportDao看起来像这样:

public class ImplReportDao implements ReportDao {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public List<Report> findAll() {
        System.out.println("find all");
        List<Report> result = new ArrayList<Report>();
        Connection conn = null;     
        try {
            if (dataSource != null) {
                System.out.println("dataSource != null");
            } else {
                System.out.println("dataSource == null");
            }

            conn = dataSource.getConnection();
            PreparedStatement statement = conn.prepareStatement("select * from reports");
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Report report = new Report();
                report.setId(resultSet.getInt("id"));
                report.setParentId(resultSet.getInt("parent_id"));
                report.setName(resultSet.getString("name"));
                result.add(report);
            }
            return result;
        } catch (Exception ex) {
            return null;
        }
    }
}

And Main class looks like: 类看起来像:

public class Main {
    private static ReportDao reportDao = new ImplReportDao();

    public static void main(String[] args) {
        List<Report> reports = reportDao.findAll();
        for (Report report : reports) {
            System.out.println("report: " + report.getName());
        }
    }
}

But after launch I've got the error NullPointerException because in ImplReportDao.findAll() dataSource is null. 但是启动后,我得到了NullPointerException错误,因为在ImplReportDao.findAll() dataSource为null。 How can I check whether h2 embedded database is created? 如何检查是否创建了h2嵌入式数据库?

You configure your databae in Spring but then create object using constructor. 您可以在Spring中配置数据仓库,然后使用构造函数创建对象。 You do not create Spring context that is why database is not created. 您没有创建Spring上下文,这就是为什么不创建数据库的原因。 Also because you use constructor Spring cannot inject datasource into your newly created object because Spring IoC container doesn't know about it. 同样因为使用构造函数,Spring无法将数据源注入到新创建的对象中,因为Spring IoC容器对此一无所知。

So you need to make several changes in your code and config XML. 因此,您需要在代码和配置XML中进行一些更改。

First, to use p:dataSource-ref you need to add this line into heade of your XML file: xmlns:p="http://www.springframework.org/schema/p" right after xmlns:jdbc="http://www.springframework.org/schema/jdbc" . 首先,要使用p:dataSource-ref您需要将此行添加到XML文件的标题中: xmlns:p="http://www.springframework.org/schema/p"紧接在xmlns:jdbc="http://www.springframework.org/schema/jdbc"

Second you need to instantiate Spring context like this 其次,您需要像这样实例化Spring上下文

public class Main {

  public static void main(String[] args) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml"); //assuming app-context.xml is in classpath of project
    ReportDao reportDao = ctx.getBean(ReportDao.class); //Ask Spring to gice you DAO object with injected dataSource
    List<Report> reports = reportDao.findAll();
    for (Report report : reports) {
        System.out.println("report: " + report.getName());
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM