spring-boot集成H2内存数据库

什么是H2 database?

H2是一个短小精干的嵌入式数据库引擎,主要的特性包括:

1、免费、开源、快速;

2、嵌入式的数据库服务器,支持集群;

3、提供JDBC、ODBC访问接口,提供基于浏览器的控制台管理程序;

4、Java编写,可使用GCJ和IKVM.NET编译;

5、短小精干的软件,1M左右。


开始集成

pom.xml


    
       org.springframework.boot
       spring-boot-starter-parent
       1.3.3.RELEASE
     
   
  
    
      junit
      junit
    
   
    
    
       org.springframework.boot
       spring-boot-starter-web
    
   
    
    
       org.springframework.boot
       spring-boot-starter-data-jpa
    
 
   
     
     
        com.h2database 
        h2
         runtime
    
   
  


启动App.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}



实体Demo.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Demo {
@Id@GeneratedValue
private Long id;
private String name;
private int age;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

dao层DemoDao.java

import org.springframework.data.repository.CrudRepository;
import cn.com.zjq.entity.Demo;

public interface DemoDao extends CrudRepository{
Demo findByName(String name);
}


测试DemoController.java

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.com.zjq.dao.DemoDao;
import cn.com.zjq.entity.Demo;
 
@RestController
public class DemoController {
   
    @Autowired
    private DemoDao demoDao;
   
    @RequestMapping("save")
    public String save(){
       Demo demoInfo = new Demo();
       demoInfo.setName("张三");
       demoInfo.setAge(20);
       demoDao.save(demoInfo);
      
       demoInfo = new Demo();
       demoInfo.setName("李四");
       demoInfo.setAge(30);
       demoDao.save(demoInfo);
      
       return "ok";
    }
   
    @RequestMapping("find")
    public List find(){
       return (List) demoDao.findAll();
    }
   
    @RequestMapping("findByName")
    public Demo findByName(){
       return demoDao.findByName("张三");
    }
}


说明

以上配置项目关闭,数据则消失,添加以下配置到配置文件,可存入本地:

spring.jpa.show-sql = true 
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url = jdbc\:h2\:file\:D\:\\testdb
#spring.datasource.url = jdbc:h2:file:~/.h2/testdb
spring.datasource.username = sa
spring.datasource.password = sa
spring.datasource.driverClassName =org.h2.Driver

spring.jpa.show-sql = true 显示sql语句
spring.jpa.hibernate.ddl-auto = update 这个必须加,每次启动对应实体


你可能感兴趣的:(H2,spring-boot,javaWeb)