【SpringBoot】通过RestAPI获取用户信息(初学者)

所需的东西

    1. 实体类Employee.java

 

    1. 存储库接口EmployeeRepository.java

 

    1. 主类(首先被调用的类)SampleApplication.java

 

    1. RestController类Con.java

 

    1. 应用程序属性文件DB信息保存文件

 

    build.gradle(主要依赖项)

源代码

@Entity
@Table(name="m_emp")
public class Employee {
    @Id
    @Column(name="empno")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String empname;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getEmpname() {
        return empname;
    }
    public void setEmpname(String empname) {
        this.empname = empname;
    }
}
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
@SpringBootApplication
public class SampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }
}
@RestController
public class Con {
    @Autowired
    EmployeeRepository empRepository;
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        List<Employee> emplist=empRepository.findAll();
        model.addAttribute("emplist", emplist);
        return emplist.toString();
    }
}
spring.datasource.url=jdbc:mysql://localhost:3306/db名
spring.datasource.username=root
//brew installでパスワードを指定していない場合はパスワードは不要
#spring.datasource.password=mysql
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=update
plugins {
    id 'org.springframework.boot' version '2.1.8.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    developmentOnly
    runtimeClasspath {
        extendsFrom developmentOnly
    }
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
        compile('org.springframework.boot:spring-boot-starter-data-jpa')
        compile('org.springframework.boot:spring-boot-starter-thymeleaf')
        compile('org.springframework.boot:spring-boot-starter-web')
        runtime('org.springframework.boot:spring-boot-devtools')
        runtime('mysql:mysql-connector-java')
        compileOnly('org.projectlombok:lombok')
        implementation('org.springframework.boot:spring-boot-starter-tomcat')
        testCompile('org.springframework.boot:spring-boot-starter-test')
}

广告
将在 10 秒后关闭
bannerAds