SpringBoot整合StringData JPA

时间:2024-05-25 13:35:50

SpringBoot整合StringData JPA

application.yml

spring:
datasource:
url: jdbc:mysql://192.168.0.169:3306/jpa
username: root
password: xiaoyan
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
# 如果表不存在或已更新,则自动创建/更新
ddl-auto: update
# 显示sql语句
show-sql: true

User.class

package kim.nzxy.demo.pojo;

import javax.persistence.*;

/**
* @Author: Xiaoyan
* @Date: 2019/3/27 14:31
*/
// 表示这是一个实体
@Entity
//对应的表明
@Table(name = "user")
public class User {
//表示主键
@Id
// 自增长
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
// 这里什么也没写,也没问题,而且自动创建的字段为user_name
String userName;
//这是和数据表对应的一个列,默认是属性名,可以不写,但是默认长度是255
@Column(name = "password", length = 50)
String password;
}

UserRepository.java

package kim.nzxy.demo.repository;

import kim.nzxy.demo.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository; /**
* JpaRepository<类, 主键类型>
* @Author: Xiaoyan
* @Date: 2019/3/27 15:05
*/
public interface UserRepository extends JpaRepository<User, Integer> {
}

UserController

package kim.nzxy.demo.controller;

import kim.nzxy.demo.pojo.User;
import kim.nzxy.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; /**
* @Author: Xiaoyan
* @Date: 2019/3/27 15:11
*/
@RestController
public class UserController {
private final UserRepository userRepository; @Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
} @RequestMapping("getUser")
public List<User> getUser() {
return userRepository.findAll();
}
}

只要将这些文件放对了地方,启动起来,基本上就算是入门了,毕竟这是一个相对来说很简单的框架了,如果SpringBoot已经入门了,这个基本上看一遍就懂了,其具体语法还请去官网大佬博客去看,我也只是为了知道它是个什么东西,我更喜欢mybatis