SpringBoot 数据访问-jpa
JPA
JPA(Java Persistence API)是 Java 持久化规范,它为关系型数据库访问提供了一种对象关系映射(ORM)的解决方案。在 Spring Boot 中,结合 JPA 可以极大地简化数据库访问的开发工作。
@Entity
注解:用于标记一个 Java 类为实体类,该类将与数据库中的表对应。
package com.ktjiaoyu.crm.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "sys_user")
//@NamedQueries(@NamedQuery(name = "User.findUsersByName", query = "select u from User u where u.usrName= ?1"))
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "usr_id")
private Long usrId;
@Column(name = "usr_name")
private String usrName;
@Column(name = "usr_password")
private String usrPassword;
// @Column(name = "usr_role_id")
// private Long usrRoleId;
@ManyToOne(targetEntity = Role.class)
@JoinColumn(name = "usr_role_id")
private Role role;
@Column(name = "usr_flag")
private Integer usrFlag;
public User() {
}
public User(String usrName, String usrPassword, Role role, Integer usrFlag) {
this.usrName = usrName;
this.usrPassword = usrPassword;
this.role = role;
this.usrFlag = usrFlag;
}
public Long getUsrId() {
return usrId;
}
public void setUsrId(Long usrId) {
this.usrId = usrId;
}
public String getUsrName() {
return usrName;
}
public void setUsrName(String usrName) {
this.usrName = usrName;
}
public String getUsrPassword() {
return usrPassword;
}
public void setUsrPassword(String usrPassword) {
this.usrPassword = usrPassword;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getUsrFlag() {
return usrFlag;
}
public void setUsrFlag(Integer usrFlag) {
this.usrFlag = usrFlag;
}
}
@Repository
注解:用于标记数据访问层的组件类,通常用于数据库操作的方法定义
package com.ktjiaoyu.crm.repository;
import com.ktjiaoyu.crm.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Long>{
// List<User> findByUsrNameLike(String usrName);
//
// @Query(value = "select u from User u where u.usrRoleId=:roleId")
// List<User> findByRoleId(@Param("roleId") Long roleId);
//
// @Transactional(timeout = 10)
// @Modifying
// @Query("update User u set u.usrName=?1 where u.usrId=?2")
// int modifyNameById(String usrName,Long roleId);
//
// List<User> findUsersByName(String usrName);
//
// @Query("select u from User u where u.usrRoleId=?1")
// Page<User> findPageByUsrRoleId(Long roleId, Pageable pageable);
}
JpaRepository
接口:Spring Data JPA 提供的核心接口,继承自PagingAndSortingRepository
和CrudRepository
,提供了丰富的数据库操作方法,如增删改查、分页和排序等。
配置
在application.properties
或application.yml
文件中进行数据库连接等配置。
spring.application.name=SpringBootJPA
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
#??JPA????
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
测试
package com.ktjiaoyu.crm;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.repository.RoleRepository;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
//@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTester {
// @Resource
// private UserRepository userRepository;
@Resource
private RoleRepository roleRepository;
@Test
public void testAdd(){//测试级联新增
Role role=new Role("测试角色","演示级联新增角色和用户",1);
User user1=new User("测试用户1","123456",role,1);
User user2=new User("测试用户2","123456",role,1);
role.getUsers().add(user1);
role.getUsers().add(user2);
roleRepository.save(role);//新增角色的同时新增关联的用户
}
//级联删除
@Test
public void testDelete() {//测试级联删除
//先使用getOne方法获取到Role的引用,然后调用delete方法删除
Role role = roleRepository.getOne(9L);
roleRepository.delete(role);
}
@Test
public void testsGet(){//测试按主键查询角色,输出关联角色数量
Role role=roleRepository.findById(2L).get();
System.out.println("roleName "+role.getRoleName());
System.out.println("users.size "+role.getUsers().size());
}
// @Test
// public void testGet(){//测试按注解查询用户,关联获得
// User user=userRepository.findById(2L).get();
// System.out.println("usrName "+user.getUsrName());
// System.out.println("roleName "+user.getRole().getRoleName());
// }
// @Resource
// private UserService userService;
// @Test
// public void testInsert(){
// User user = new User("JPA","123456",2L,1);
// userRepository.save(user);
// }
//
// @Test
// public void testGet(){
// User user = userRepository.findById(6L).get();
// System.out.println("usrName:"+user.getUsrName());
// }
//
// @Test
// public void testFindByUsrNameLike(){
// List<User> list = userRepository.findByUsrNameLike("%s%");
// if (list != null){
// for (User user : list){
// System.out.println("usrName:"+user.getUsrName());
// }
// }
// }
//
//
//
// @Test
// public void testFindPageByUsrRoleId(){
// int page=0,size=4;
// Sort sort = Sort.by(Sort.Direction.DESC,"usrId");
// Pageable pageable = PageRequest.of(page,size,sort);
// Page<User> userPage = userRepository.findPageByUsrRoleId(9L,pageable);
// System.out.println("总记录数:"+userPage.getTotalElements());
// System.out.println("总页数:"+userPage.getTotalPages());
// System.out.println("当前页数:"+userPage.getNumber()+1);
// System.out.println("每页记录数:"+userPage.getSize());
// System.out.println("当前页记录数:"+userPage.getNumberOfElements());
// for (User user : userPage.getContent()){
// System.out.println("usrId:"+user.getUsrId());
// }
// }
//
//
//
//
// @Test
// public void testFindPageByMap(){
// int page=0,size=5;
// Sort sort = Sort.by(Sort.Direction.DESC,"usrId");
// Pageable pageable = PageRequest.of(page,size,sort);
// Map param = new HashMap();
// param.put("roleId",3L);
// Page<User> userPager = userService.findPageByMap(param,pageable);
// System.out.println("总记录数 -----> "+userPager.getTotalElements());
// System.out.println("总页数 -----> "+userPager.getTotalPages());
// System.out.println("当前页数-----> "+userPager.getNumber());
// System.out.println("当前记录数 -----> "+userPager.getSize());
// System.out.println("当前页记录 -----> ");
// for (User user : userPager.getContent()){
// System.out.println("usrId:"+user.getUsrId());
// }
// }
}
总结
简化开发:减少了大量的 SQL 编写工作,通过对象操作数据库。
可维护性高:代码更加清晰、易于理解和维护。
数据库无关性:可以在不同的数据库之间轻松切换,只需更改配置。
强大的查询功能:支持方法命名查询和使用 JPQL(Java Persistence Query Language)进行复杂查询。