<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- 在application.yml文件中添加数据库和jap
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai
username: root
password: 123456
druid:
initial-size: 5 #连接池初始化大小
min-idle: 10 #最小空闲连接数
max-active: 20 #最大连接数
web-stat-filter:
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #不统计这些请求数据
stat-view-servlet: #访问监控网页的登录用户名和密码
login-username: druid
login-password: druid
jpa:
hibernate:
#更新或者创建数据库表结构
ddl-auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
#控制台显示SQL
show-sql: true
@Data
@Entity
@Table(name = "test")
public class Test {
@Column
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column(name="phone")
private Integer phone;
}
- 创建 Repository
创建一个 Repository 接口,继承自 JpaRepository,用于对实体类进行 CRUD 操作。
public interface TestRepository extends JpaRepository<Test, Long> {
}
@Service
public class TestService {
@Autowired
private TestRepository testRepository;
public Test save( Test test) {
return testRepository.save(test);
}
public Test findById(Long id) {
return testRepository.findById(id).orElse(null);
}
public List<Test> findAll() {
return testRepository.findAll();
}
public void deleteById(Long id) {
testRepository.deleteById(id);
}
}
- 如果使用Repository接口需要在启动应用程序上添加注解@EnableJpaRepositories
如果在项目中仅对数据库添加或更新字段,不使用Repository可不添加注解@EnableJpaRepositories
@SpringBootApplication
@EnableJpaRepositories
public class ApiApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}