天天看點

關于記憶體資料庫h2的簡單demo

h2是一個輕量級的記憶體資料庫,配置簡單,啟動速度快。

springboot預設配置好了h2的配置資訊,我們直接使用h2資料庫即可

<!-- jar依賴的版本控制,需要導入springboot的parent依賴 -->
<dependencies>
  	<dependency>
  		<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-devtools</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-web</artifactId>
  	</dependency>
  	<!-- 對資料庫操作的依賴 -->
  	<dependency>
  		<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-data-jpa</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>com.h2database</groupId>
  		<artifactId>h2</artifactId>
  		<scope>runtime</scope>
  	</dependency>
  </dependencies>
           

該POJO在程式啟動時會生成對應的表

@Entity 
public class User {

	@Id
	@GeneratedValue
	private long id;
	private String title;
	private String content;
	public User(String title, String content) {
		this.title = title;
		this.content = content;
	}
	public User() {
		super();
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
}
           

UserRepository 無需實作,CrudRepository提供了基本的增删改查的方法了

public interface UserRepository extends CrudRepository<User, Long> {

}
           

運作的時候h2資料庫才存在,可以對資料庫進行操作

(如果想在容器啟動的時候執行sql檔案,使用jdbc:initialize-database,用法 百度)

@RestController
public class HelloController {
	
	@Autowired
	private UserRepository userRepository;
	
	@RequestMapping("/save")
	public String save(){
		userRepository.save(new User("title1", "content1"));
		userRepository.save(new User("title2", "content2"));
		userRepository.save(new User("title3", "content3"));
		userRepository.save(new User("title4", "content4"));
		userRepository.save(new User("title5", "content5"));
		userRepository.save(new User("title6", "content6"));
		return "save ok";
	}
	
	@RequestMapping("/findAll")
	public Iterable<User> findAll(){
		return userRepository.findAll();
	}
	
}
           

application.yml可以不配置,也可以正常使用h2資料庫

這兒的配置,主要是為了對資料進行持久化處理(存入檔案中),否則應用重新開機,資料丢失

spring: 
  datasource: 
    url: jdbc:h2:file:~/.h2/testdb # ~ 對應 C:\Users\administrator 使用者目錄
    username: sa
    password: sa
    driverClassName: org.h2.Driver
  jpa: 
    hibernate: 
      ddl-auto: update #如果資料庫沒有對應的表則建立,有則更新
           

持久化生成的檔案

關于記憶體資料庫h2的簡單demo