[spring-boot] 配置数据库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/crazyman2010/article/details/70903807

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’

配置数据库
新建数据库:

create database db_example;
create user 'root'@'localhost' identified by '123456'; -- Creates the user
grant all on 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")
public class User {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   private String nickName;
   private Integer sex;

   public Long getId() {
       return id;
   }

   public void setId(Long id) {
       this.id = id;
   }

   public String getNickName() {
       return nickName;
   }

   public void setNickName(String nickName) {
       this.nickName = nickName;
   }

   public Integer getSex() {
       return sex;
   }

   public void setSex(Integer sex) {
       this.sex = sex;
   }
}

创建repository

public interface UserRepository extends CrudRepository<User,Long> {
}

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

猜你喜欢

转载自blog.csdn.net/crazyman2010/article/details/70903807