我的Spring启动有问题。 我创建了Entity和Repository,但Repository中的方法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;
}
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 :(得分: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,看看你的&#34; application.properties&#34;是正确的。这是我的例子:
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!