//本文做者:cuifuanjava
什么是JPA?mysql
一种规范,并不是ORM框架,也就是ORM上统一的规范git
用了以后能够作什么,为何要用?redis
代码解释:spring
实体类sql
package com.example.springredis.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.io.Serializable; @Entity @Data public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String account; private String pwd; }
dao层数据库
@Repository public interface UserDao extends JpaRepository<User, Long> { }
测试类api
@Autowired private UserDao userDao; public void findAllTest() { System.out.println(userDao.findAll().toString()); }
上面的操做已经完成了一个查询所有,相信不用在作多余的解释了springboot
JPA优势:主要就是简单易用,集成方便,能够不用写SQL语句app
这里的环境
这里使用的是Gradle
下载以后请在IDEA导入项目
buildscript { ext { springBootVersion = '2.1.0.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java-library' apply plugin: 'idea' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } } //Gradle3.4新增了Java-library插件,java-library插件使用了新的依赖配置implementation和api。旧的依赖配置compile被废弃 dependencies { implementation('org.springframework.boot:spring-boot-starter-data-jpa') implementation('mysql:mysql-connector-java') compileOnly('org.projectlombok:lombok') testImplementation('org.springframework.boot:spring-boot-starter-test') }
package com.example.springbootjpademo.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String ename; protected User() { } public User(String name, String ename) { this.name = name; this.ename = ename; } @Override public String toString() { /* JAVA字符串格式化-String.format() %s 字符串类型 %d 整数类型(十进制) */ return String.format("Customer[id=%d, name='%s', ename='%s']", id, name, ename); } }
这里很简单,直接继承核心接口JpaRepository
src/main/java/com/example/springbootjpademo/repository/UserRepository.java
package com.example.springbootjpademo.repository; import com.example.springbootjpademo.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { }
修改application.properties 为 application.yml
src/main/resources/application.yml
spring: # 数据源配置 datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false username: root password: 123456 jpa: # 在 SrpingBoot 2.0 版本中,Hibernate 建立数据表的时候,默认的数据库存储引擎选择的是 MyISAM #(以前好像是 InnoDB,这点比较诡异)。这个参数是在建表的时候,将默认的存储引擎切换为 InnoDB 用的。 database-platform: org.hibernate.dialect.MySQL5InnoDBDialect # spring.jpa.show-sql=true 配置在日志中打印出执行的 SQL 语句信息。 show-sql: true # 配置指明在程序启动的时候要删除而且建立实体类对应的表。 # create 这个参数很危险,由于他会把对应的表删除掉而后重建。因此千万不要在生成环境中使用。只有在测试环境中,一开始初始化数据库结构的时候才能使用一次。 # ddl-auto:create----每次运行该程序,没有表格会新建表格,表内有数据会清空 # ddl-auto:create-drop----每次程序结束的时候会清空表 # ddl-auto:update----每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新(推荐) # ddl-auto:validate----运行程序会校验数据与数据库的字段类型是否相同,不一样会报错 hibernate.ddl-auto: update
src/test/java/com/example/springbootjpademo/SpringbootJpaDemoApplicationTests.java
package com.example.springbootjpademo; import com.example.springbootjpademo.repository.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootJpaDemoApplicationTests { @Autowired private UserRepository userRepository; @Test public void contextLoads() { System.out.println(userRepository.findAll().toString()); } }
若是出现下列等错误:
Error:(41, 13) java: 找不到符号 符号: 方法 setName(java.lang.String) 位置: 类型为com.example.springbootjpademo.entity.User的变量 user
请注意下面的设置是否正确:
src/test/java/com/example/springbootjpademo/SpringbootJpaDemoApplicationTests.java
package com.example.springbootjpademo; import com.example.springbootjpademo.entity.User; import com.example.springbootjpademo.repository.UserRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootJpaDemoApplicationTests { @Autowired private UserRepository userRepository; @Test public void contextLoads() { System.out.println(userRepository.findAll().toString()); } @Before public void add() { userRepository.save(new User("英雄联盟", "lol")); } //修改操做 @After public void update() { // ifPresent 若是存在值,则使用值调用指定的使用者,不然不执行任何操做。 userRepository.findById(1L).ifPresent(user -> { user.setName("xiugaihou"); userRepository.save(user); System.out.println(user.toString()); }); } //删除 @After public void del() { userRepository.findById(2L).ifPresent(user -> userRepository.delete(user)); } }
最后数据库的值: