一、springbootJPA介绍
1、JPA介绍
JPA是Java持久层API ;
说明:可以实现以对象的方式操作数据库,并且内部实现了数据的CURD等操作,通过反射机制实现的;
1)添加JPA的jar包
<!--添加jpa的组件--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
<!--添加mysql的组件--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> |
2)导入数据库的SQL文件
3)配置yum配置文件
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8 username: root password: root jpa: show-sql: true hibernate: ddl-auto: update |
3)编辑pojo对象
@Entity 实体:可以根据该实体创建数据表
//实体:可以根据该实体创建数据表
@Entity
public class User {
@Id //定义主键信息
@GeneratedValue //表示主键自增
private Integer id;
private String name;
private Integer age;
private String sex;
set..() , get..() ;
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
4)编辑UserDao接口文件
|
5)编辑UserService.java
public interface UserService {
List<User> findAll();
void saveUser(User user);
void updateUser(User user);
List<User> findUserByName(User user);
}
6)编辑UserServiceImpl.java
@Transactional(propagation=Propagation.REQUIRED) //需要事务控制
|
说明:使用JPA查询时,如果需要指定条件查询,需要编辑特定的方法.查看方法的格式参数表格文件,如下:
JPA的语法规则
关键字 | 方法命名 | sql where字句 |
And | findByNameAndPwd | where name= ? and pwd =? |
Or | findByNameOrSex | where name= ? or sex=? |
Is,Equals | findById,findByIdEquals | where id= ? |
Between | findByIdBetween | where id between ? and ? |
LessThan | findByIdLessThan | where id < ? |
LessThanEquals | findByIdLessThanEquals | where id <= ? |
GreaterThan | findByIdGreaterThan | where id > ? |
GreaterThanEquals | findByIdGreaterThanEquals | where id > = ? |
After | findByIdAfter | where id > ? |
Before | findByIdBefore | where id < ? |
IsNull | findByNameIsNull | where name is null |
isNotNull,NotNull | findByNameNotNull | where name is not null |
Like | findByNameLike | where name like ? |
NotLike | findByNameNotLike | where name not like ? |
StartingWith | findByNameStartingWith | where name like '?%' |
EndingWith | findByNameEndingWith | where name like '%?' |
Containing | findByNameContaining | where name like '%?%' |
OrderBy | findByIdOrderByXDesc | where id=? order by x desc |
Not | findByNameNot | where name <> ? |
In | findByIdIn(Collection<?> c) | where id in (?) |
NotIn | findByIdNotIn(Collection<?> c) | where id not in (?) |
True | findByAaaTue | where aaa = true |
False | findByAaaFalse | where aaa = false |
IgnoreCase | findByNameIgnoreCase | where UPPER(name)=UPPER(?) |