Jpa的基本使用(本次实践课用到的)
- Jpa是什么
JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
- 安装IDEA旗舰版,学生授权申请方式
- 创建Springboot项目
- 删除application.properties文件
- 添加application.yml文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
#library为数据库名
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
properties:
hibernate:
format_sql: true
server:
port: 8181
- 以创建实体类Book为例
@Entity
@Data
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增
private Integer id;
private String author;
private String name;
}
- 创建接口类BookRepo
public interface BookRepo extends JpaRepository<Book,Integer> {
}
- 创建控制层BookHandle
@RestController
@RequestMapping("/book")
public class BookHandle {
@Autowired
private BookRepo bookRepository;
@GetMapping("/findAll")
public List<Book> findAll(){
return bookRepository.findAll();
}
}
- 如上,/book/findAll接口获取表中所有信息
- bookRepository.findAll();//select * from book
- bookRepository.findById(id);//按主键查找
- bookRepository.findAllByAuthor(str);//select * from book where author = str;
- bookRepository.deleteById(id);//按主键删除
- bookRepository.save(book);//增加或修改book对象
- 参考博客:SpringBoot整合SpringData与JPA