SpringBoot开发日记(二)——连接数据库

 在application.properties中添加:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/hzktest?serverTimezone=UTC
spring.datasource.username=******
spring.datasource.password=******
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

写Controller层


@RestController
public class UserController {

    @Autowired
    private UserRepository userRepo;

    @GetMapping(value = "/user")
    public List<User> userList(){
        return userRepo.findAll();
    }

}

写Dao层


..
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User,Integer> {
}

这里要说一下pom.xml需要引入maven库才可以继承JpaRepository:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

写entity:


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue
    private Integer id;
    private String age;
    private String name;

    public Integer getId() {
        return id;
    }

    public User() {
    }

    public User(Integer id, String age, String name) {
        this.id=id;
        this.age = age;
        this.name = name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

最终的目录结构为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值