spring boot——集成JPA——入门示例001
需要新增的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
pom文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | <?xml version= "1.0" encoding= "UTF-8" ?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion> 4.0 . 0 </modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version> 2.2 . 6 .RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mohai.one</groupId> <artifactId>springboot-data-jpa</artifactId> <version> 0.0 . 1 -SNAPSHOT</version> <name>springboot-data-jpa</name> <description>spring-data-jpa整合实现</description> <properties> <java.version> 1.8 </java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional> true </optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> |
application.yml配置信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | spring: datasource: driver- class -name: com.mysql.cj.jdbc.Driver url: jdbc:mysql: //127.0.0.1:3306/mohai_demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull username: root password: 123456 # JPA配置 jpa: # 数据库类型 database: mysql # 切换默认的存储引擎切换为InnoDB database-platform: org.hibernate.dialect.MySQL5InnoDBDialect # 输出日志中打印出执行的SQL语句 show-sql: true # 配置程序在启动的时候自动操作实体类对应的表 hibernate: #create:程序重新启动时,都会重新创建表,会造成数据会丢失 #create-drop:每次运行程序时,会先创建表结构,然后待程序结束时清空表 #upadte:每次运行程序时,实体对应没有表时会创建表,如果实体发生改变会更新表结构,原来数据不会清空只会更新 #validate:每次运行程序时,会校验数据与数据库的字段类型是否相同 ddl-auto: update |
UserEntity类
package com.mohai.one.springbootjpa.domain; import javax.persistence.*; @Entity //必选注解,声明和数据库中user表关联 @Table(name = "user") //可选注解,声明实体对应的表信息 public class UserEntity { @Id // 表名实体唯一标识 @GeneratedValue(strategy = GenerationType.IDENTITY) //主键自动生成策略 private Integer id; //@Column定义列名和属性,默认为字段名 @Column private String name; @Column private int age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserRepository
package com.mohai.one.springbootjpa.repository; import com.mohai.one.springbootjpa.domain.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserRepository extends JpaRepository<UserEntity,Integer> { List<UserEntity> findAllByName(String name); @Modifying @Query(value = "insert into user(id,name,age) values(:id,:name,:age)",nativeQuery = true) int insertNameAndAge(@Param("id") Integer id, @Param("name") String name, @Param("age") int age); }
UserService
package com.mohai.one.springbootjpa.service; import com.mohai.one.springbootjpa.domain.UserEntity; import com.mohai.one.springbootjpa.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @Service public class UserService { @Autowired private UserRepository userRepository; //查 public List<UserEntity> getAll(){ return userRepository.findAll(); } //查 public List<UserEntity> findAllByName(String name){ return userRepository.findAllByName(name); } //通过id查询 public UserEntity getOne(Integer id){ return userRepository.findById(id).get(); } //改 @Transactional public UserEntity updateUser(UserEntity userEntity){ return userRepository.saveAndFlush(userEntity); } //增 @Transactional public int insertUser(UserEntity userEntity){ return userRepository.insertNameAndAge(userEntity.getId(),userEntity.getName(),userEntity.getAge()); } //删 @Transactional public void deleteUserById(Integer id){ userRepository.deleteById(id); } }
UserController
package com.mohai.one.springbootjpa.controller; import com.mohai.one.springbootjpa.domain.UserEntity; import com.mohai.one.springbootjpa.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @Created by moerhai@qq.com */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/findAll") public List<UserEntity> findAll(){ return userService.getAll(); } @RequestMapping("/findAllByName") public List<UserEntity> findAllByName(String name){ return userService.findAllByName(name); } //通过主键Id查询 @RequestMapping("/getOne/{id}") public UserEntity getUserById(@PathVariable Integer id){ return userService.getOne(id); } @RequestMapping("/save") public int save(@RequestBody UserEntity userEntity){ return userService.insertUser(userEntity); } @RequestMapping("/edit") public UserEntity edit(@RequestBody UserEntity userEntity){ return userService.updateUser(userEntity); } @RequestMapping("/delete") public int delete(@RequestParam("id") Integer id){ userService.deleteUserById(id); return 1; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
2021-05-29 自动化——测试开发进阶——Django——初始化数据库(ORM模型与数据库表)——sqlite3数据库
2021-05-29 APP——内存测试——python持续获取内存值