在IDEA中新建maven项目
添加依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.175</version>
</dependency>
</dependencies>
其中spring-jdbc 和spring-context是spring的包
H2是一个轻量级的关系数据库。
打开h2数据库
在库文件中找到org.h2.tools.Console类,作为java应用程序运行。即可在网页中运行h2数据库。
创建springbean配置类
@org.springframework.context.annotation.Configuration
public class Configuration {
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:tcp://localhost/~/test");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
}
使用DriverMangerDataSource类创建dataSource,并设置dataSource的驱动,url,用户名,密码。
在h2中建立account表
create table account(
ID bigint identity primary key,
OWNER_NAME varchar(255),
BALANCE double,
ACCESS_TIME timestamp,
LOCKED boolean)
创建Main类
public class Main {
public static void main(String[] args) throws SQLException {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Configuration.class);
DataSource dataSource = applicationContext.getBean("dataSource",DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection.isClosed());
connection.close();
System.out.println(connection.isClosed());
}
}
创建Main类先创建Spring容器,然后获取dataSource的bean实例。
检查连接是否成功。