版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34173549/article/details/80876966
JPA(Java Persistence API)java持久化规范。
只需要编写一个接口继承一个类就可以进行操作
-
<dependency>
-
<groupId>mysql </groupId>
-
<artifactId>mysql-connector-java </artifactId>
-
</dependency>
-
-
-
<dependency>
-
<groupId>org.springframework.boot </groupId>
-
<artifactId>spring-boot-starter-data-jpa </artifactId>
-
</dependency>
-
-
public class User {
-
//使用这个注解id必须是int
-
-
-
private long id;
-
private String name;
-
-
"yyyy-MM-dd HH:mm:ss")(format=
-
private Date date;
-
-
false)(serialize=
-
private String notSerilized;
-
-
public String getNotSerilized() {
-
return notSerilized;
-
}
-
public void setNotSerilized(String notSerilized) {
-
this.notSerilized = notSerilized;
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
public Date getDate() {
-
return date;
-
}
-
public void setDate(Date date) {
-
this.date = date;
-
}
-
public long getId() {
-
return id;
-
}
-
public void setId(long id) {
-
this.id = id;
-
}
-
-
}
会根据@id和@GeneratedValue生成数据主键:注意如果使用GeneratedValue那么逐渐必须不是String
生成字段的原则是驼峰 比如oldName --OLD_NAME
repository
创建repository接口继承CRUDRopository
-
public interface UserRepository extends CrudRepository<User, Integer>{
-
-
}
-
-
public class UserService {
-
-
-
private UserRepository userRepository;
-
-
-
public void save(User user){
-
userRepository.save(user);
-
}
-
-
-
public void delete(User user){
-
userRepository.delete(user);
-
}
-
-
-
public Iterable<User> findAll(){
-
return userRepository.findAll();
-
}
-
}
-
-
"/user")(value=
-
public class UserController {
-
-
-
private UserService userService;
-
-
/* @RequestMapping("/save")
-
public String save(@RequestParam(required=false) User user){
-
userService.save(user);
-
return "save ok";
-
}*/
-
-
"/delete")(
-
public String delete(@RequestParam(required=false) User user){
-
userService.delete(user);
-
return "delete ok";
-
}
-
-
"/getAll")(
-
public Iterable<User> findAll(){
-
return userService.findAll();
-
}
-
-
"/saveById")(
-
public String saveByName(@RequestParam String name){
-
User user = new User();
-
user.setName(name);
-
user.setDate( new Date());
-
userService.save(user);
-
return "save ok";
-
}
-
}
2. 若我们定义的接口继承了Repository,则该接口会被IOC容器识别为一个Repository Bean纳入到IOC容器中,进而可以在该接口中定义满足一定规范的方法。
3. 实际上也可以通过@RepositoryDefinition,注解来替代继承Repository接口。
4. 查询方法以find | read | get开头;
5. 涉及查询条件时,条件的属性用条件关键字连接,要注意的是条件属性以首字母大写。
6.使用@Query注解可以自定义JPQL语句实现更灵活的查询。
PagingAndSortingRepository
该接口提供了分页与排序功能
--Iterable<T> findAll(Sort sort); //排序
--Page<T> findAll(Pageable pageable); //分页查询(含排序功能)