[spring-boot] 配置数据库

2022-10-11 12:07:25

guide:
https://spring.io/guides/gs/accessing-data-jpa/
https://spring.io/guides/gs/accessing-data-mysql/

增加依赖
compile ‘org.springframework.boot:spring-boot-starter-data-jpa’
compile ‘mysql:mysql-connector-java’

配置数据库
新建数据库:

createdatabase db_example;createuser'root'@'localhost' identifiedby'123456';-- Creates the usergrantallon db_example.*to'root'@'localhost';-- Gives all the privileges to the new user on the newly created database

然后在src/main/resources/application.properties中配置如下:

spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=root
spring.datasource.password=123456

创建实体类
创建User.java作为实体类,数据会被映射到这个类
不要导入:import org.springframework.data.annotation.Id;
请导入import javax.persistence.Id;

@Entity@Table(name ="user")publicclassUser {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;private String nickName;private Integer sex;public LonggetId() {return id;
   }publicvoidsetId(Long id) {this.id = id;
   }public StringgetNickName() {return nickName;
   }publicvoidsetNickName(String nickName) {this.nickName = nickName;
   }public IntegergetSex() {return sex;
   }publicvoidsetSex(Integer sex) {this.sex = sex;
   }
}

创建repository

publicinterfaceUserRepositoryextendsCrudRepository<User,Long> {
}

现在就可以使用jpa-data的API来访问数据库了。

  • 作者:M_O_
  • 原文链接:https://blog.csdn.net/crazyman2010/article/details/70903807
    更新时间:2022-10-11 12:07:25