Spring Data JPA:介绍:
Spring Data就是spring提供操作数据库的框架,而Spring Data JPA只是Spring Data框架下的一个基于JPA标准操作数据库的模块。
Spring Data JPA:基于JPA的标准对数据进行操作。简化持久层的代码,只需要写接口。
SpringBoot整合Spring Data JPA
1、添加依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
2、添加application.yml配置信息:
#mysql数据库驱动 url username password
#数据库连接池
#正向工程
#控制台输出sql
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=trueusername: rootpassword: roottype: com.alibaba.druid.pool.DruidDataSourcejpa:hibernate:ddl-auto: updateshow-sql: true
新建数据库
3、添加实体类
@Entity
@Table(name = "t_users")
@Data
public class Users {/*** @Id:表明id是主键* @GeneratedValue:生成策略*/@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")private Integer id;@Column(name = "name")private String name;@Column(name = "age")private Integer age;@Column(name = "address")private String address;
}
4、添加持久层接口
/*** 参数1:当前将要映射的实体类* 参数2:当前将要映射的实体类中id主键类型*/
public interface UsersRepository extends JpaRepository<Users,Integer> {
}
5、在pom文件中添加测试启动类的坐标
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
6、新建启动类
@SpringBootApplication
public class SpringBootDataJpaApplication {public static void main(String[] args) {SpringApplication.run(SpringBootDataJpaApplication.class, args);}
}
编写测试代码
我们要在test包下,新建com.gblfy.repository包(与上面的java包结构保持一致):
新建测试类UsersRepositoryTest继承Springboot生成的test类,这样做的好处就是:不用每个测试类都在类上添加测试注解,只需要继承共有的测试类即可(和接口实现类原理一样)
@RunWith(SpringRunner.class)
@SpringBootTest
public class UsersRepositoryTest {@Autowiredprivate UsersRepository usersRepository;@Testpublic void saveUser(){Users u = new Users();u.setName("zhangdan");u.setAge(25);u.setAddress("beijing");usersRepository.save(u);}
}
10、运行效果图:
查看数据库:
1、是否生成t_users表
2、是否将数据成功插入数据库
本文源码下载:
github地址:
https://github.com/gb-heima/Spring-Boot-Actual-Combat/tree/master/parent/spring-boot-chapter-9