SpringBoot整合JPA
JPA是什么?
JPA (Java Persistence API)Java持久化API。是一套Sun公司Java官方制定的ORM 方案,是规范,是标准 ,sun公司自己并没有实现
导入Maven
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
-
这里用到的是mysql数据库,所以还要导入MySQL的依赖!
配置
-
application.yaml
配置 -
server: port: 80 spring: # 配置数据库链接 datasource: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # jpa主要配置 jpa: show-sql: true # 默认false,在日志里显示执行的sql语句 database: mysql hibernate.ddl-auto: update #指定为update,每次启动项目检测表结构有变化的时候会新增字段,表不存在时会新建,如果指定create,则每次启动项目都会清空数据并删除表,再新建 properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect # 使用JPA创建表时,默认使用的存储引擎是MyISAM,通过指定数据库版本,可以使用InnoDB database-platform: org.hibernate.dialect.MySQL5Dialect hibernate: naming: #指定jpa的自动表生成策略,驼峰自动映射为下划线格式 implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl #physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
-
数据库的用户名和密码哟啊配置自己的!!!
编码
-
实体类
-
这里还实现了添加数据时自动插入创建时间
-
package com.blog.demo.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * @author mucd * @time 2022/2/6 12:46 */ @Data @AllArgsConstructor @NoArgsConstructor //声明这个是表的实体类 @Entity //重要 @EntityListeners(AuditingEntityListener.class) @Table(name = "sys_user") public class SysUser implements Serializable { /** * GeneratedValue 指定主键生成策略 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; //@Column 是表中的字段名 @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "user_status") private String userStatus; /** * 自动插入创建时间 */ @Column(name = "create_date") @CreatedDate //时间格式 @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss") private Date createDate; public SysUser(Integer id, String username, String password, String userStatus) { this.id = id; this.username = username; this.password = password; this.userStatus = userStatus; } }
-
-
dao接口
-
@Repository public interface SysUserDao extends JpaRepository<SysUser,Integer> { }
-
没错 dao接口什么都不用写,因为常用的增删改查 分页等方法在JpaRepository这个类中都已经被封装好了,我们使用的话直接调用就好了
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7UQbSEPN-1644128207131)(C:\Users\mucd\AppData\Roaming\Typora\typora-user-images\1644126939462.png)]
-
如果需要自定义方法的话,那么就在dao中按照规定编写即可.
-
-
service类
-
为了省事这里的service没有用接口,直接就是用了类.
-
package com.blog.demo.service; /** * @author mucd * @time 2022/2/6 13:10 */ import com.blog.demo.dao.SysUserDao; import com.blog.demo.entity.SysUser; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class SysUserService { @Resource private SysUserDao sysDao; /** * 查询所有数据 * * @return list */ public List<SysUser> getSysDao() { final List<SysUser> all = sysDao.findAll(); System.out.println("all = " + all); return all; } /** * 添加数据 * @param user user * @return object */ public Object addUser(SysUser user) { final SysUser sysUser1 = sysDao.saveAndFlush(user); System.out.println("save = " + sysUser1); return sysUser1; } /** * 定时任务 自动执行 */ @Scheduled(cron = " 1/5 * * * * * ") public void excel() { final SysUser sysUser = new SysUser(); sysUser.setUsername("abcd"); sysUser.setUserStatus("正常"); sysUser.setPassword("passad"); System.out.println(this.addUser(sysUser)); } }
-
-
controller
-
package com.blog.demo.controller; import com.blog.demo.entity.SysUser; import com.blog.demo.r.Result; import com.blog.demo.service.SysUserService; 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.RestController; import javax.annotation.Resource; /** * @author mucd * @time 2022/2/6 13:11 */ @RestController @RequestMapping("/sys") public class SysUserController { @Resource private SysUserService userService; @GetMapping("/findAll") public Object findAll() { return new Result<Object>(200, "查询成功", userService.getSysDao()); } @PostMapping("save") public Object save() { final SysUser sysUser = new SysUser(); sysUser.setUsername("abcd"); sysUser.setUserStatus("正常"); sysUser.setPassword("passad"); final Object o = userService.addUser(sysUser); return new Result<Object>(200, "添加成功", o); } }
-
-
启动类
-
package com.blog.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.scheduling.annotation.EnableScheduling; /** * @author mucd */ @SpringBootApplication @EnableJpaAuditing @EnableScheduling public class BlogDemoApplication { public static void main(String[] args) { SpringApplication.run(BlogDemoApplication.class, args); } }
-
-
终于可以测试了,我这里使用的是Apifox
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-phlZzmC3-1644128207132)(C:\Users\mucd\AppData\Roaming\Typora\typora-user-images\1644127872681.png)]
-
查询ok
-
添加会自动添加,因为设置了定时任务,可以看到里面的数据都是定时任务添加进去的,我们还可以手动测试一下添加功能
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fNCBWRyl-1644128207133)(C:\Users\mucd\AppData\Roaming\Typora\typora-user-images\1644128167381.png)]
-
ok 简单的整合完成