最近项目中使用了jpa作为持久层技术框架,记录一下项目使用中的一些心得。
jpa基本概念
JPA是一个ORM框架;基于hibernate框架进行了进一步的封装;提供更加简单的数据操作
基本使用
<!--maven依赖:-->
<!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--querydsl-->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<scope>provided</scope>
</dependency>
<!--编译插件-->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
//position:repo包 ;持久层接口继承
public interface TestRepository extends JpaRepository<Test, String>,QuerydslPredicateExecutor<Test>{
Test findByType(String type);//jpa会按照接口名称规则查询数据库
}
//position:api包;标准接口
@RestController
@RequestMapping("/v1")
@Slf4j
public class TestAPI {
@Autowired
TestRepository testRepository;
@RequestMapping(value = "/test",method = RequestMethod.POST)
@ResponseBody
public Test addData(@RequestBody Test test){
log.info(String.format("新增[%s]", test));
return testRepository.save(test);
}
@RequestMapping(value = "/test",method = RequestMethod.PUT)
@ResponseBody
public Test updateData(@RequestBody Test test){
log.info(String.format("更新[%s]", test));
return testRepository.save(test);
}
@RequestMapping(value = "/test/{id}",method = RequestMethod.DELETE)
@ResponseBody
public Map<String, Boolean> deleteData(@PathVariable String id){
log.info(String.format("删除记录,主键为[%s]", id));
try{
testRepository.deleteById(id);
}catch(EmptyResultDataAccessException e){
log.debug(String.format("删除记录错误[%s]", e.getMessage()));
throw new CommonJsonException("","删除记录错误",e.getMessage());//自定义异常
}
return new HashMap<String, Boolean>(){{ put("success",true);}};
}
@RequestMapping(value = "/test",method= RequestMethod.GET)
@ResponseBody
public Page<Test> getAllData(@QuerydslPredicate(root = Test.class) Predicate predicate, @PageableDefault(value=30) Pageable pageable){
return testRepository.findAll(predicate,pageable);//分页查询
}
}
//Entity实体:
@Entity
@Table(name = "test")
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper=false)
@Accessors(chain=true)
public class Test implements Serializable{
private static final long serialVersionUID = -1220435668368653691L;
@Id
@Column(name = "id")
@GeneratedValue(generator="jpa-uuid")
@GenericGenerator(name="jpa-uuid",strategy="uuid")
private String id;
//名称
@Column(name = "name")
private String name;
//类型
@Column(name = "type")
private String type;
}
//entity实体可以定义实体之间的关联关系,如一对多、一对一、多对一
//多对一
@ManyToOne(fetch=FetchType.EAGER)
@NotFound(action= NotFoundAction.IGNORE)
@JoinColumn(name="a_id",referencedColumnName="b_id",updatable=false,insertable=false)
@ToString.Exclude
private B b;
//一对多
@OneToMany(fetch=FetchType.LAZY)
@JoinColumn(name="b_id",referencedColumnName = "a_id",updatable = false,insertable = false)
@ToString.Exclude
private List<A> aList;