1. 概述
Spring Data JPA是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,可以使开发者用极简的代码即可对数据库的访问合操作,它提供了包括增删改查等在内的常用功能,且易于扩展、提高开发效率。
2. 引入核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
3. yml配置信息
server:
port: 8105
spring:
application:
name: springboot-jpa
datasource:
#type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://xx.xx.xx.xx:3306/springboot?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: 用户名
password: 密码
hikari:
minimum-idle: 10 #最小空闲连接,默认10
maximum-pool-size: 20 #最大连接数
idle-timeout: 600000 #空闲连接超时时间,默认600000(10分钟)
max-lifetime: 540000 #连接最大存活时间,默认30分钟
connection-timeout: 60000 #连接超时时间,默认30秒
connection-test-query: SELECT 1 #测试连接是否可用查询语句
jpa:
hibernate:
ddl-auto: update #数据库表生成策略
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
show-sql: true #控制台显示sql语句
database: mysql
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
4. 持久层接口
@Repository
public interface SysUserRepository extends JpaRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {
@Query(value = "from sys_user user where user.userName = ?1")
SysUser findUserByUserName(String userName);
@Query(value = "update sys_user set userName = ?2 where id = ?1")
@Modifying
int updateUserById(Long id, String userName);
@Query(value = "select * from sys_user where user_code = :userCode", nativeQuery = true)
SysUser findUserByUserCode(String userCode);
}
说明:JpaRepository接口用于实现基本增删改查操作,JpaSpecificationExecutor接口用于实现复杂查询(分页查询)
Spring Data JPA可以使用接口定义的方式查询,也支持JPQL方式和SQL语句查询
5. 业务层接口
public interface SysUserService {
/**
* 新增用户信息
* @param user
* @return
*/
SysUser insertUser(SysUser user);
/**
* 修改用户信息
* @param user
* @return
*/
SysUser updateUser(SysUser user);
/**
* 根据ID查询用户信息
* @param id
* @return
*/
SysUser selectUserById(Long id);
/**
* 根据ID查找用户信息
* @param id
* @return
*/
Optional<SysUser> findById(Long id);
/**
* 查询所有用户信息
* @return
*/
List<SysUser> findAll();
/**
* 根据ID删除用户信息
* @param id
*/
void deleteById(Long id);
/**
* 根据用户名称查询用户信息(使用jpql查询)
* @param userName
* @return
*/
SysUser findUserByUserName(String userName);
/**
* 根据用户编号查询用户信息(使用sql查询)
* @param userCode
* @return
*/
SysUser findUserByUserCode(String userCode);
/**
* 根据ID更新用户信息(使用jpql更新)
* @param id
* @param userName
* @return
*/
int updateUserById(Long id, String userName);
/**
* 使用Specification实现条件查询
* @param userName
* @return
*/
List<SysUser> selectUserBySpecification(String userName);
/**
* 多条件分页查询
* @param pageNum
* @param pageSize
* @param userName
* @return
*/
Page<SysUser> selectPageUserBySpecification(int pageNum, int pageSize, String userName);
}
6. 业务层接口实现类
@Service
public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserRepository userRepository;
@Override
public SysUser insertUser(SysUser user) {
return userRepository.save(user);
}
@Override
public SysUser updateUser(SysUser user) {
return userRepository.save(user);
}
@Override
public SysUser selectUserById(Long id) {
return userRepository.getOne(id);
}
@Override
public Optional<SysUser> findById(Long id) {
return userRepository.findById(id);
}
@Override
public List<SysUser> findAll() {
return userRepository.findAll();
}
@Override
public void deleteById(Long id) {
userRepository.deleteById(id);
}
@Override
public SysUser findUserByUserName(String userName) {
return userRepository.findUserByUserName(userName);
}
@Override
public SysUser findUserByUserCode(String userCode) {
return userRepository.findUserByUserCode(userCode);
}
@Override
@Transactional(rollbackFor = Exception.class)
public int updateUserById(Long id, String userName) {
return userRepository.updateUserById(id, userName);
}
@Override
public List<SysUser> selectUserBySpecification(String userName) {
Specification<SysUser> specification = new Specification<SysUser>() {
@Override
public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.like(root.get("userName").as(String.class), "%" + userName + "%");
}
};
return userRepository.findAll(specification);
}
@Override
public Page<SysUser> selectPageUserBySpecification(int pageNum, int pageSize, String userName) {
Specification<SysUser> specification = new Specification<SysUser>() {
@Override
public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicateList = new ArrayList<>();
if (StringUtils.hasLength(userName)) {
predicateList.add(criteriaBuilder.like(root.get("userName").as(String.class), "%" + userName + "%"));
}
return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
}
};
Pageable pageable = PageRequest.of(pageNum, pageSize);
return userRepository.findAll(specification, pageable);
}
}
7. 查询方法命名规则
只需要按照Spring Data JPA提供的方法命名规则定义方法的名称,就可以完成查询工作。Spring Data JPA在程序执行的时候会根据方法名称进行解析,并自动生成查询语句进行查询。
Keyword | Sample | JPQL snippet |
---|---|---|
Distinct | findDistinctByLastnameAndFirstname | select distinct … where x.lastname = ?1 and x.firstname = ?2 |
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is, Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull, Null | findByAge(Is)Null | … where x.age is null |
IsNotNull, NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection<Age> ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> ages) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstname) = UPPER(?1) |
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/76790.html