与其他数据库一样,配置配好即可 demo是使用hibernate jpa映射数据库
导入h2的jar包即可使用一个没有安装过的数据库 pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
springboot入口
package com.h2demo.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String\[\] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
实体bean 映射数据库
@Entity
public class User {
@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;
}
}
controller层
@RestController
public class DemoController {
@Autowired
private UserDao userDao;
@RequestMapping("save")
public String save() {
User user = new User();
user.setName("xiaohong");
user.setAge(15);
userDao.save(user);
user = new User();
user.setName("xiaoming");
user.setAge(16);
userDao.save(user);
return "ok";
}
@RequestMapping("find")
public List<User> find() {
return (List<User>) userDao.findAll();
}
@RequestMapping("findByName")
public User findByName() {
return userDao.findByName("xiaohong");
}
}
JPA接口
public interface UserDao extends CrudRepository<User, Long>{
User findByName(String name);
}
配置文件
//是否打印sql语句
spring.jpa.show-sql=true
//ddl执行方式,update create 等
spring.jpa.hibernate.ddl-auto=update
//数据库地址 `存放地址`
spring.datasource.url=jdbc:h2:file:~/.h2/testdb
//用户名
spring.datasource.username=aa
//密码
spring.datasource.password=aa
//驱动
spring.datasource.driverClassName=org.h2.Driver
//控制台查看数据库的路径 localhost:8080/h2-console
spring.h2.console.path=/h2-console
//是否启用h2控制台
spring.h2.console.enabled=true
//外网是否能连接到h2
spring.h2.console.settings.web-allow-others=true