springboot JPA 操作
程序员文章站
2022-05-02 09:39:12
...
1.新建一个user类
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class User {
private Long id;
private String username;
private String password;
@Id
@Column(name = "id", nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "username", nullable = true, length = 255)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "password", nullable = true, length = 255)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(id, username, password);
}
}
2.新建UserRepository 接口类集成 JpaRepository,这样就可以用使用 PagingAndSortingRepository接口类和 QueryByExampleExecutor接口类的一些基本的查询方法
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface UserRepository extends JpaRepository<User, Long> {
/**
* 通过名称找到用户。
*
* @param username 用户名
* @return 单个用户
*/
User findByUsername(String username);
/**
* 通过名称和年龄找到用户
*
*
* @param username 用户名
* @param password 密码
* @return 单个用户。
*/
User findByUsernameAndPassword(String username, String password);
/**
* 通过名称模糊查询并分页
*
* @param username 用户名
* @return 用户集合。
*/
Page<User> findByUsernameLike(String username, Pageable pageable);
/**
* 使用hql查询:name对应@Param里的name
*
* @param username 用户名
* @return 用户
*/
@Query("from User u where u.username=:username")
User findByHQL(@Param("username") String username);
/**
* 使用sql查询?1表示第一个参数,?2表示第二个参数 #{#entityName}自动获取实体类的table name
*
* @param username 用户名
* @param password 密码
* @return 用户
*/
@Query(value = "select * from #{#entityName} where username = ?1 and password = ?2", nativeQuery = true)
User findBySQL(@Param("username") String username,@Param("password") String password);
}
3. 编写测试类 TestJpa
import com.jpa.dao.UserRepository;
import com.jpa.entity.User;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
/**
* @Author: renbaojia
* @CreateDate: 2019-04-17 17:38:50
* @Description: 测试jpa的增删改查 级联查询
* @Version: 3.4.0
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestJpa {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
// 注入userRepository
@Autowired
private UserRepository userRepository;
@Test
public void find() {
log.debug("jpa接口方法--------------------------------");
log.debug("jpa查询--------------------------------");
//主键查询
User user1 = userRepository.getOne(1L);
//是否存在的id
userRepository.existsById(1L);
//查询所有
List<User> all = userRepository.findAll();
//查询符合主键的所有
List<Long> a = new ArrayList<>();
a.add(1L);
a.add(2L);
List<User> allById = userRepository.findAllById(a);
//查询所有,id降序
List<User> id = userRepository.findAll(Sort.by("id").descending());
//分页根据id降序查询
Pageable pageable =PageRequest.of(1,1, Sort.Direction.DESC,"id");
Page<User> page = userRepository.findAll(pageable);
System.out.println("总页数:"+page.getTotalPages()+"当前页:"+page.getPageable().getPageNumber());
log.debug("save or update--------------------------------");
User user=null;
//保存或修改 立即 flush
userRepository.saveAndFlush(user);
//保存或修改
userRepository.save(user);
//批量保存
List<User> list=new ArrayList<>();
userRepository.saveAll(list);
log.debug("delete--------------------------------");
userRepository.delete(user);
//删除所有,一条一条执行
userRepository.deleteAll();
//单个删除
userRepository.deleteAll(list);
//批量执行,一条语句
userRepository.deleteAllInBatch();
//根据主键删除
userRepository.deleteById(1l);
//批量删除
userRepository.deleteInBatch(list);
//统计所有行数
long count = userRepository.count();
//自定义方法
//模糊查询
Page<User> admin4 = userRepository.findByUsernameLike("%admin%", PageRequest.of(0, 1, Sort.Direction.ASC, "username"));
log.info(admin4.getTotalPages() + "");
// log.debug("QueryByExampleExecutor 接口方法--------------------------------");
/*<S extends T> Optional<S> findOne(Example<S> var1);
<S extends T> Iterable<S> findAll(Example<S> var1);
<S extends T> Iterable<S> findAll(Example<S> var1, Sort var2);
<S extends T> Page<S> findAll(Example<S> var1, Pageable var2);
<S extends T> long count(Example<S> var1);
<S extends T> boolean exists(Example<S> var1);*/
log.debug("findAll--------------------------------------");
User user2 = new User();
user2.setUsername("admin");
Example<User> example = Example.of(user2);
List<User> one = userRepository.findAll(example, Sort.by("username").descending());
log.info("findAll:" + one.size());
log.debug("findOne---------------------------------");
User user3 = new User();
user3.setId(1L);
Example<User> example1 = Example.of(user3);
Optional<User> user4 = userRepository.findOne(example1);
log.info("findOne:" + user4.get().getPassword());
log.debug("count---------------------------------");
User user5 = new User();
user5.setId(1L);
Example<User> example2 = Example.of(user3);
long count1 = userRepository.count(example2);
log.info("count:" + count1);
log.debug("findAll 模糊查找--------------------------------------");
User user6 = new User();
user6.setUsername("admin");
ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("username", ExampleMatcher.GenericPropertyMatchers.startsWith());
Example<User> example3 = Example.of(user2,exampleMatcher);
List<User> one2 = userRepository.findAll(example3, Sort.by("username").descending());
log.info("findAll 模糊查找:" + one2.size());
//根据hql查询用户名
User admin = userRepository.findByHQL("admin");
log.debug("根据hql查询用户名:" + admin.getUsername());
//根据sql查询用户名
User admin1 = userRepository.findBySQL("admin", "123456");
System.out.println("根据sql查询用户名:" + admin1.getUsername());
log.debug("根据sql查询用户名:" + admin1.getUsername());
//根据用户名和密码查询
User admin2 = userRepository.findByUsernameAndPassword("admin", "123456");
log.debug("根据用户名和密码查询:" + admin2.getUsername());
//根据用户名查询
User admin3 = userRepository.findByUsername("admin");
log.debug("根据用户名查询:" + admin3.getUsername());
}
}
项目源码 https://github.com/SmallRen/springboot-jpa
觉得不错给个小星星
上一篇: docker运行jar包加载外部配置文件
下一篇: 如何让前任男友主动找你复合