Spring Boot 之 JPA 和 Controller接收参数

在pom.xml中添加依赖包

		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			mysql
			mysql-connector-java
			runtime
		

在application.properties中增加数据库配置

注意spring.jpa.properties.hibernate.hbm2ddl.auto的选择,create每次都会重新建表

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=!QAZ2wsx
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql= true

增加模型类

@Entity
@Data
public class User implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue
	private Long id;
	
	@Column(nullable = false, unique = true)
	private String userName;
	
	@Column(nullable = false)
	private String passWord;
	
	@Column(nullable = false)
	private String email;
	
	@Column(nullable = true)
	private String nickName;
	
	@Column(nullable = false)
	private String regTime;
}

增加模型接口

public interface UserRepository extends JpaRepository {
}

增加接收参数并操作数据库

@RestController
public class UserController {
	
	@Autowired
    private UserRepository userRepository;
	
    @RequestMapping("/list")
    public List list() {
    	return userRepository.findAll();
    }
    
    @RequestMapping("/add")
    // /add?userName=c&passWord=c&email=c®Time=c&nickName=c
    public List add(
    		@RequestParam(name = "userName") String userName,
    		@RequestParam(name = "passWord") String passWord,
    		@RequestParam(name = "email") String email,
    		@RequestParam(name = "regTime") String regTime,
    		@RequestParam(name = "nickName") String nickName) {
    
    	User user = new User();
    	user.setUserName(userName);
    	user.setPassWord(passWord);
    	user.setEmail(email);
    	user.setRegTime(regTime);
    	user.setNickName(nickName);
    	userRepository.save(user);
    	return userRepository.findAll();
    }
    
    @RequestMapping("/del/{id}")
    // /del/{1}
    public List del(@PathVariable(name = "id") Long id) {
    
    	userRepository.deleteById(id);
    	return userRepository.findAll();
    }

}

接收参数的几种形式

参考:https://blog.csdn.net/suki_rong/article/details/80445880

  • get: url/{id}
  • get: url?name=
  • post:
  • request header
  • cookie

提示时区错误的应对

  • 修改mysql时区,参考 https://www.cnblogs.com/shiqiangqiang/p/8393662.html
  • 如果需要使用gmt+8时区,在数据库连接url后添加:?serverTimezone=GMT%2B8

参考文档

  • http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html
  • http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html
  • https://www.jianshu.com/p/c23c82a8fcfc

你可能感兴趣的:(Java)