2016-11-21 108 views
0

我有一個Spring引導的問題。 我創建了實體和存儲庫,但存儲庫中的方法findByName不起作用。 我的網址:findByName不工作[Spring boot]

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; 
} 

BaseEntity:

@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 
+0

@javaguy閱讀關於RepositoryRestResource,它是像控制器一樣工作。 – Mello007

回答

0

我建議你創建一個資源類,就像控制器一樣工作。這裏一個簡單的例子:

@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!