【问题标题】:findByName isn't work [Spring boot]findByName 不起作用 [Spring boot]
【发布时间】:2016-11-21 18:47:52
【问题描述】:

我在使用 Spring Boot 时遇到问题。 我创建了实体和存储库,但存储库中的 findByName 方法不起作用。 我的网址:

http://localhost:8080/student/search/findByName?name=Artem 在 Google chrome 中:找不到 localhost,但已映射搜索。

实体:

@Getter @Setter
@Entity @Table(name = "Student")

public class Student extends BaseEntity{
    private String name;
    private String dateOfBirthDay;
    private String sex;
    private String phoneNumber;
}

基础实体:

@Getter
@Setter
@MappedSuperclass
public class BaseEntity {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column protected Long id;

我的仓库:

@RepositoryRestResource(collectionResourceRel = "student", path = "student")
public interface StudentRepository extends PagingAndSortingRepository<Student, Long> {
    Student findByName(@Param("name") String name);
}

应用:

@SpringBootApplication
@EnableTransactionManagement

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Application.yaml:

spring:
    application:
        name: students
    datasource:
        driverClassName: org.postgresql.Driver
        url: jdbc:postgresql://localhost:5432/students
        username: postgres
        password: postgres
    jpa:
      hibernate:
        ddl-auto: update
server:
    port: 8080

【问题讨论】:

  • @javaguy 了解 RepositoryRestResource,它就像控制器一样工作。

标签: spring spring-boot


【解决方案1】:

我建议你创建一个资源类,像控制器一样工作。这里举个简单的例子:

@RestController
@RequestMapping("/yourPath") //students, whatever
public class StudentsResource {

@Autowired
private StudentRepository studentRepository;

//type media that you want to show (json, xml...in this case is JSON)
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })

// <Student> is the entity, object
@RequestMapping(value = "/yourPath/{studentName}")
public ResponseEntity<Student> findByName(@pathVariable("studentName") String name) {
    Student student = studentRepository.findByName(name);

    if(student == null){
     //handler your own exception here
    }

    //show the student as json object
    return ResponseEntity.status(HttpStatus.OK).body(student);
}

注意:这是资源类。但是你的问题是关于 localhost,所以如果你使用的是 Spring Boot,请查看你的“application.properties”是否正确。这是我的例子:

spring.datasource.url=jdbc:mysql://localhost:3306/yourDataBase
spring.datasource.username=yourUser
spring.datasource.password=yourPassword

spring.jpa.hibernate.ddl-auto=update //makes the spring create the database automatic!

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2014-08-12
    相关资源
    最近更新 更多