drop table user if exists;
create table user(
id bigint(5) primary key AUTO_INCREMENT,
name varchar(30),
sex varchar(12),
);
3 在src/main/resources下添加文件data.sql,用于启动时插入测试数据
insert into user(id,name,sex) values (1,'牛','男');
insert into user(id,name,sex) values (2,'鬼','女');
insert into user(id,name,sex) values (3,'蛇','女');
insert into user(id,name,sex) values (4,'神','男');
4 在配置文件application.properties添加相关常用的配置(可根据需求更改)
# 启用SQL语句的日志记录
spring.jpa.show-sql = true
# 设置ddl模式
spring.jpa.hibernate.ddl-auto = none
# 数据库连接设置
spring.datasource.driver-class-name =org.h2.Driver
spring.datasource.url = jdbc:h2:mem:dbc2m
# 指定的静态配置路径
#spring.datasource.url = jdbc:h2:file:D:/db/.h2/dbc2m;AUTO_SERVER=TRUE
# 数据库连接账号
spring.datasource.username = sa
# 数据库连接密码
spring.datasource.password = sa
# 数据初始化设置,每次启动程序,程序都会运行resources/schema.sql文件,对数据库的结构进行操作。
spring.datasource.schema=classpath:db/schema.sql
# 数据初始化设置,每次启动程序,程序都会运行resources/data.sql文件,对数据库的数据操作。
spring.datasource.data=classpath:db/data.sql
# h2 web console设置,表明使用的数据库平台是h2
spring.datasource.platform=h2
# 远程访问支持配置进行该配置后,h2 web consloe就可以在远程访问了。否则只能在本机访问。
spring.h2.console.settings.web-allow-others=true
# 配置访问h2 web consloe的路径,即 YOUR_URL/h2-console(YOUR_URL是程序的访问URl)。
spring.h2.console.path=/h2-console
# 程序开启时默认会启动h2 web consloe,如果不想启动h2 web consloe,可设置为false。
spring.h2.console.enabled=true
5 创建实体类
@table(name=”user”)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private String sex;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
}
注:@Id :声明被标注的属性与数据表的主键形成映射关系
@GeneratedValue(strategy = GenerationType.IDENTITY):声明主键的生成策略
@Column:用来标识实体类中属性与数据表中字段的对应关系
@Table:标注实体类,其name属性表示与实体类对应的表的名称,默认表明为实体类的名称