JAVA-(4)-学习Java 开源框架Spring 连接数据库

mac2024-05-10  33

spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root

源码下载地址:https://github.com/spring-guides/gs-accessing-data-mysql.git     

https://spring.io/guides/gs/accessing-data-mysql/

https://download.csdn.net/download/ldy889/11946349

 

# # Structure for table "user" # DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '', `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; package com.example.accessingdatamysql; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller // This means that this class is a Controller @RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController { @Autowired // This means to get the bean called userRepository // Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository; @PostMapping(path="/add") // Map ONLY POST Requests public @ResponseBody String addNewUser (@RequestParam String name , @RequestParam String email) { // @ResponseBody means the returned String is the response, not a view name // @RequestParam means it is a parameter from the GET or POST request User n = new User(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved"; } @GetMapping(path="/all") public @ResponseBody Iterable<User> getAllUsers() { // This returns a JSON or XML with the users return userRepository.findAll(); } }

D:\java\app\SpringApp\gs-rest-service-master\gs-rest-service-master\complete\build

 

测试还不知道如何测试。大概是这样吧

 

这里比较重要的是userRepository,它其实是一个接口,

package com.example.accessingdatamysql; import org.springframework.data.repository.CrudRepository; import com.example.accessingdatamysql.User; // This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository // CRUD refers Create, Read, Update, Delete public interface UserRepository extends CrudRepository<User, Integer> { }

它能执行以下11个方法:save  saveAll findById existsById findAll findAllById count deleteById delete deleteAll deleteAll

有兴趣的可以查下   https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html

最新回复(0)