目录
1.mysql数据库环境的搭建(建库、建表)
数据库增加jpa的配置:
#--------------jpa配置 start --------------#
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
# 打印sql日志
spring.jpa.show-sql=true
#--------------jpa配置 start --------------#
2.JPA的定义
JPA是Java Persistence API规范的简称,中文名Java持久层API,描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
spring-boot-starter-data-jpa默认用hibernate实现。
3.maven坐标
<!-- 连接数据库依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- jpa依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
spring-boot-starter-data-jpa 引入JPA的依赖,有了这个依赖,springboot2.x会自动扫描jpa的实体和接口到IoC。
4.建表t_user对应的实体类@Entity
建立java类和表的映射关系。
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**与表t_user对应的实体类 */
@Entity // 实体类
@Table(name = "t_user") // 对应的表名
public class UserEntity {
@Id // 主键
@GeneratedValue(strategy = GenerationType.IDENTITY) // 主键策略,递增
private int id;
@Column(name = "name") // 属性和表字段的映射
private String name;
@Column(name = "sex")
private int sex;
@Column(name = "note")
private String note;
// setters and getters ...
}
5.数据库操作接口JpaRepository
需要继承接口JpaRepository<实体类, 主键类型>。
其中的方法都是按照一定的规则命名的自定义方法。
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.zyf.springDb.jpa.entity.UserEntity;
/**
* 操作数据库的接口 extends JpaRepository<实体类, 主键类型>
*/
public interface UserJpaRepository extends JpaRepository<UserEntity, Integer> {
// 模糊查询,自定义方法,需要按照字段规则命名:findBy+字段名+Like
public List<UserEntity> findByNameLike(String name);
// 模糊查询,自定义方法,需要按照字段规则命名:findBy+字段名+Like+Or+字段名+Like
public List<UserEntity> findByNameLikeOrNoteLike(String name, String note);
// 模糊查询,自定义方法,需要按照字段规则命名:findBy+字段名+Like+And+字段名+Like
public List<UserEntity> findBySexAndNoteLike(int sex, String note);
}
6.JPA对数据库的基本操作
JpaRepository已经提供了常用的单表操作方法,如findAll()、findById()、save()和delete()等,这下方法可以直接调用。
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zyf.springDb.jpa.dao.UserJpaRepository;
import com.zyf.springDb.jpa.entity.UserEntity;
@Service
public class UserEntityService {
/** 注入操作数据库的接口 */
@Autowired
private UserJpaRepository userJpaRepository;
/** 查询所有用户 */
public List<UserEntity> findAll() {
return userJpaRepository.findAll();// findAll方法为jpa自带
}
/** 根据主键查询用户 */
public UserEntity findById(int id) {
Optional<UserEntity> optional = userJpaRepository.findById(id);// findById方法为jpa自带
return optional == null ? null : optional.get();
}
/** 新建用户 */
public UserEntity save(UserEntity user) {
UserEntity res = userJpaRepository.save(user);// save方法为jpa自带
return res;
}
/** 删除用户 */
public void delete(UserEntity user) {
// userJpaRepository.delete(user);// delete方法为jpa自带
userJpaRepository.deleteById(user.getId());// deleteById方法为jpa自带
}
/** 根据用户名模糊查询 */
public List<UserEntity> findByNameLike(UserEntity user) {
// findByNameLike方法为在UserJpaRepository自定义,需要按照字段规则
return userJpaRepository.findByNameLike("%" + user.getName() + "%");
}
/** 根据用户名or备注模糊查询 */
public List<UserEntity> findByNameLikeOrNoteLike(UserEntity user) {
// findByNameLikeOrNoteLike方法为在UserJpaRepository自定义,需要按照字段规则
return userJpaRepository.findByNameLikeOrNoteLike("%" + user.getName() + "%","%" + user.getNote() + "%");
}
/** 根据用户名or备注模糊查询 */
public List<UserEntity> findBySexAndNoteLike(UserEntity user) {
// findByNameLikeOrNoteLike方法为在UserJpaRepository自定义,需要按照字段规则
return userJpaRepository.findBySexAndNoteLike(user.getSex(),"%" + user.getNote() + "%");
}
}
7.自定义sql操作数据库 - JPQL
entity定义改造:
/**
* 与表t_user对应的实体类
*/
@Entity(name = "userEnt") // 实体类
@Table(name = "t_user") // 对应的表名
public class UserEntity {
...
}
JpaRepository增加JPQL方法:
// JPQL:自定义sql,此处语法【from + entity的名称】即@Entity(name = "userEnt")中定义的名称
@Query("from userEnt where name like concat('%',?1,'%') or note like concat('%',?2,'%')")
public List<UserEntity> findByNameAndNote(String name, String note);
JPQL中 from userEnt 拼接的是实体类的bean名称,即在entity声明的@Entity(name = "userEnt")。
8.总结
- spring-boot-starter-data-jpa 引入JPA的依赖,有了这个依赖,springboot2.x会自动扫描jpa的实体和接口到IoC。代码中并没有做扫描jpa得策略。
- jpa的关键在于@Entity和表的映射。
- jpa对单表操作很有优势,可不用写sql。
- 通过相关规则创建方法名,jpa自动完成查询。
- jpa对于复杂的查询,操作不便。
github:https://github.com/zhangyangfei/SpringBootLearn 其中的springDb工程。