SpringBoot JPA使用配置过程详解
jpa是什么? jpa(java persistence api)是sun官方提出的java持久化规范. 为java开发人员提供了一种对象/关联映射工具来管理java应用中的关系数据. 它的出现是为了简化现有的持久化开发工作和整合orm技术. 结束各个orm框架各自为营的局面.
jpa 其实是一种规范,它的实现中比较出名的是 hibernate 框架;
1、pom 引入依赖:
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-jpa</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <scope>runtime</scope> <version>5.1.18</version> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid-spring-boot-starter</artifactid> <version>1.1.10</version> </dependency>
2、添加配置文件
#数据库连接信息
spring.datasource.type=com.alibaba.druid.pool.druiddatasource
spring.datasource.username=root
spring.datasource.password=521hui
spring.datasource.url=jdbc:mysql://localhost:3306/test
#jpa设置
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.database-platform=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.mysql57dialect
3、编写 bean
@entity(name = "t_book") public class book { @id @generatedvalue(strategy = generationtype.identity) private integer id; private string name; private string author; 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 string getauthor() { return author; } public void setauthor(string author) { this.author = author; } @override public string tostring() { return "book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + '}'; } }
4、编写 接口
public interface bookdao extends jparepository<book,integer> {
}
5、启动程序,数据库创建表
6、进行 crud 测试
@autowired bookdao bookdao; @test void testinsert() { book book = new book(); book.setname("孔雀翎"); book.setauthor("古龙"); bookdao.save(book); } @test void testupdate() { book book = new book(); book.setname("笑傲江湖"); book.setauthor("金庸"); book.setid(1); bookdao.saveandflush(book); } @test void testdelete() { bookdao.deletebyid(1); } @test void testfind() { system.out.println(bookdao.findbyid(4).tostring()); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 详解Vue3中对VDOM的改进
下一篇: Java泛型机制必要性及原理解析