Java 框架常见问答和解决方案
1. 如何选择合适的 Java 框架?
2. 如何解决 Spring Bean 注入问题?
3. 如何处理 Hibernate 懒加载异常?
4. 如何解决 Struts 2 拦截器问题?
5. 如何提高 JUnit 单元测试的效率?
实战案例:使用 Spring MVC 和 MySQL 构建 CRUD(创建、读取、更新、删除)应用程序
@SpringBootApplication public class CrudApp { public static void main(String[] args) { SpringApplication.run(CrudApp.class, args); } } @Entity class Person { @Id @GeneratedValue private Long id; private String name; private int age; } @Repository interface PersonRepository extends CrudRepository<Person, Long> {} @RestController class PersonController { @Autowired private PersonRepository personRepository; @GetMapping("/person") public List<Person> getAll() { return personRepository.findAll(); } @PostMapping("/person") public Person create(@RequestBody Person person) { return personRepository.save(person); } @GetMapping("/person/{id}") public Person getById(@PathVariable Long id) { return personRepository.findById(id).orElse(null); } @PutMapping("/person/{id}") public Person update(@PathVariable Long id, @RequestBody Person person) { Person existing = personRepository.findById(id).orElse(null); if (existing != null) { existing.setName(person.getName()); existing.setAge(person.getAge()); return personRepository.save(existing); } return null; } @DeleteMapping("/person/{id}") public void delete(@PathVariable Long id) { personRepository.deleteById(id); } }
以上是Java框架的常见问答和解决方案的详细内容。更多信息请关注PHP中文网其他相关文章!