spring boot jpa - 使用封装好的方法对数据库进行增删改查

  作者:记性不好的阁主

依赖:


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>


配置application.properties


spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 若启动时发现数据库没有此表则创建表
spring.jpa.hibernate.ddl-auto=update
# 控制台显示执行的sql语句
spring.jpa.show-sql=true


项目所需配置结构




User.java 实体类


package com.laoxu.springboot.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

import javax.persistence.*;

@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"})
@Data
@Entity
@Table(name = "tb_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column(name = "name", length = 50)
private String name;
@Column
private String email;

}



UserRepository.java 为jpa操作类


package com.laoxu.springboot.repository;

import com.laoxu.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer> {

}



编写控制器,实现对数据库的操作



package com.laoxu.springboot.controller;

import com.laoxu.springboot.entity.User;
import com.laoxu.springboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
@Autowired
private UserRepository userRepository;

@RequestMapping("/user/{id}")
@ResponseBody
public User getUser(@PathVariable("id") Integer id){
User user = userRepository.getOne(id);
return user;
}
@GetMapping("/user")
@ResponseBody
public User insertUser(User user){
User save = userRepository.save(user);
return save;
}


}



自定义查询


Spring Data JPA 可以根据接⼝⽅法名来实现数据库操作,主要的语法是 findXXByreadAXXByqueryXXBycountXXBygetXXBy 后⾯跟属性名称,利⽤这个功能仅需要在定义的 Repository 中添加对应 的⽅法名即可,使⽤时 Spring Boot 会⾃动帮我们实现



Keyword
Sample
JPQL snippet
And
findByLastnameAndFirstname
… where x.lastname = ?1 and x.firstname = ?2
Or
findByLastnameOrFirstname
… where x.lastname = ?1 or x.firstname = ?2
Is,Equals
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
findByAgeIsNull
... 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 ages) 
… where x.age in ?1
NotIn
findByAgeNotIn(Collection GitChat age) 
… where x.age not in ?1
TRUE
findByActiveTrue()
… where x.active = true
FALSE
findByActiveFalse()
… where x.active = false
IgnoreCase
findByFirstnameIgnoreCase
… where UPPER(x.firstame) = UPPER(? 1)


简单demo


https://github.com/1051513344/spring-boot-jpa-demo


例子:


自定义查询


package com.neo.repository;

import com.neo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {


List<User> findAllByIdLessThan(Long maxId);

@Query(value="select * from `user` where id < 50", nativeQuery=true)
List<User> getAllUserByMaxId();

@Query(value = "update `user` set user_name='张老三' where id = ?1", nativeQuery = true)
@Modifying
@Transactional
void updateUserNameById(Long id);


}



service层调用


package com.neo.service;

import com.neo.model.User;
import com.neo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Override
public List<User> getAllUser() {
//查询所有数据
return userRepository.findAll();
}

@Override
public User getUserByExample() {
//根据条件查询
User user = new User();
user.setId(1L);
Example<User> example = Example.of(user);
return userRepository.findOne(example).get();
}

@Override
public List<User> getAllUserByPage() {
//分页+排序查询演示:
//Pageable pageable = new PageRequest(page, size);//2.0版本后,该方法以过时
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(0, 5, sort);
Page<User> users = userRepository.findAll(pageable);
return users.getContent();
}

@Override
public List<User> getUserByLessId(Long maxId) {
return userRepository.findAllByIdLessThan(maxId);
}

@Override
public List<User> getUserByMaxId() {
return userRepository.getAllUserByMaxId();
}


@Override
public void updateUserNameById(Long id) {
userRepository.updateUserNameById(id);
}

@Override
public User getUserById(Long id) {
return userRepository.findById(id).get();
}
}



相关推荐

评论 抢沙发

表情

分类选择