SpringBoot使用Spring-data-jpa访问数据库
Spring Data JPA 可以理解为 JPA 规范的再次封装抽象,底层使用了 Hibernate 的 JPA 技术实现,它可以很高效的结合spring对数据库进行访问。
很多框架都可以集成JPA,SpringBoot也不例外。
首先在pom.xml中引入依赖,这里访问的是oracle,引入的是ojdbc7
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc7</artifactId> <version>12.1.0.2</version> </dependency>
application.properties添加数据库连接池信息以及JPA的相关属性
spring.jpa.hibernate.ddl-auto的属性分为create、create-drop、update、validate
create:每次启动服务都将之前创建的表删除并根据model类重新生成新表,这种方式会导致数据丢失。
create-drop:启动服务后根据model类生成新表,但是sessionFactory一关闭,表就自动删除。
update:启动服务后根据model类生成新表,每次加载服务都会更新数据,也是最常用的属性
validate:不会生成新表,需要提前在数据库创建表,每次加载服务都会更新数据。
spring.jpa.show-sql=true:控制台打印sql输出
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1523:PREPROD spring.datasource.username=produsr spring.datasource.password= spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true
接下来创建model类,JPA会按照model类的名称和属性生成表和字段
如果是Oracle数据库,需要在id字段上指定一个序列@SequenceGenerator,JPA会根据序列的名称,为该表创建一个序列;如果是Mysql,则忽略。
allocationSize=1表示序列的值按1递增
package com.didispace.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * * @author CarryStone * @version 1.0.0 * @blog https://home.cnblogs.com/u/CarryStone * */ @Entity public class CarEitity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeqGenerator") @SequenceGenerator(name = "SeqGenerator", sequenceName = " seq_car_entity_first",allocationSize=1) private Long id; @Column(nullable=false) private String name; @Column(nullable=false) private String password; @Column(nullable=false) private Integer age; public CarEitity() {} public CarEitity(String name,String password,Integer age) { this.name = name; this.password = password; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
创建一个接口继承JpaRepository,JpaRepository自带操作数据库的方法,也可以自定义JPQL语句操作数据
需要注意的是,CarEitity实体类需要添加到JpaRepository泛型中
package com.didispace.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface CarEitityRepository extends JpaRepository<CarEitity, Long>{ CarEitity findByName(String name); CarEitity findByNameAndAge(String name,String age); @Query("from CarEitity u where u.name =:name") CarEitity findCarEntity(@Param("name") String name); }
最后用Junit进行单元测试,验证JPA是否能实现数据库的操作
package com.didispace; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.didispace.domain.CarEitity; import com.didispace.domain.CarEitityRepository; /** * * @author CarryStone * @version 1.0.0 * @blog https://home.cnblogs.com/u/CarryStone * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=Application.class) public class ApplicationTests { @Autowired private CarEitityRepository carEitityRepository; @Test public void test() throws Exception { carEitityRepository.save(new CarEitity("aaa","123456",20)); carEitityRepository.save(new CarEitity("bbb","123456",21)); carEitityRepository.save(new CarEitity("ccc","123456",22)); carEitityRepository.save(new CarEitity("ddd","123456",23)); carEitityRepository.save(new CarEitity("eee","123456",24)); Assert.assertEquals(5, carEitityRepository.findAll().size()); Assert.assertEquals(20, carEitityRepository.findCarEntity("aaa").getAge().intValue()); System.out.println("年龄是:"+carEitityRepository.findCarEntity("bbb").getAge()); } }
可以看到测试通过,数据库的表已经创建,并且数据已经成功插入。



总结起来,JPA有如下几点优势:
1.可持久化对象。JPA可直接将JAVA对象持久化到数据库中,并能够使用JPQL语言进行查询。
2.使用简单。JPA使用注释(Annotation)定义Java对象与关系数据库之间的映射,而传统的ORM多使用xml配置文件。JPA使用起来比ORM要方便。
3.规范标准化。JPA是JCP组织发布的,是Java官方规定的统一的API。目前已经有多种框架实现JPA标准。

浙公网安备 33010602011771号