Spring Data JPA的简单使用

Posted 默辨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Data JPA的简单使用相关的知识,希望对你有一定的参考价值。

Spring Data JPA的简单使用


Spring Data JPA官方地址

1、新建Spring Boot项目,引入对应的依赖

<dependencies>
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>2.7.4</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>2.7.4</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
</dependencies>

2、根据数据库信息,添加yaml配置信息

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/jpa?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: updatez

3、编写实体类,同时设置好数据库表对应的字段名字

@Table
@Entity(name = "user")
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public class User 

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "user_id")
	private Integer userId;

	@Column(name = "user_name")
	private String name;

	@Column(name = "class_name")
	private String className;

	@Column(name = "age")
	private Integer age;



4、编写mapper

public interface UserMapper extends JpaRepository<User, Integer> 

	List<User> findUsersByName(String name);

	List<User>  findByAgeAndName(Integer age, String name);


5、编写测试类

@SpringBootTest
class SpringbootjpaApplicationTests 

	@Autowired
	private UserMapper userMapper;

	/**
	 * 使用jpa自带的方法,向数据库中添加数据
	 */
	@Test
	void contextLoads() 

		userMapper.save(buildUser("mobian", "初一", 13));
		userMapper.save(buildUser("pan", "高一", 22));
		userMapper.save(buildUser("wang", "初二", 15));
	

	private static User buildUser(String name, String className, Integer age) 
		User user = new User();
		user.setClassName(className);
		user.setName(name);
		user.setAge(age);
		return user;
	

	/**
	 * 使用jpa自带的方法,查询所有的数据,再分页后返回
	 */

	@Test
	void findAll() 
		System.out.println(userMapper.findAll(PageRequest.of(1, 2)));
	

	/**
	 * 使用jpa自带的方法,根据主键id查询数据库数据
	 */
	@Test
	void findAllById() 
		System.out.println(userMapper.findById(1));
	

	/**
	 * 使用mapper中自定义的方法,不需要写sql,直接根据方法命名规则完成sql逻辑
	 */
	@Test
	void findAllByName() 
		System.out.println(userMapper.findUsersByName("mobian"));
	

	/**
	 * 使用mapper中自定义的方法,不需要写sql,直接根据方法命名规则完成sql逻辑
	 */
	@Test
	void findAllByAge() 
		System.out.println(userMapper.findByAgeAndName(22, "pan"));
	


附JPA支持的方法换sql的表格:

KeywordSampleJPQL snippet
DistinctfindDistinctByLastnameAndFirstnameselect distinct … where x.lastname = ?1 and x.firstname = ?2
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is, EqualsfindByFirstname,findByFirstnameIs,findByFirstnameEquals… where x.firstname = ?1
BetweenfindByStartDateBetween… where x.startDate between ?1 and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age <= ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNull, NullfindByAge(Is)Null… where x.age is null
IsNotNull, NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection<Age> ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection<Age> ages)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstname) = UPPER(?1)

以上是关于Spring Data JPA的简单使用的主要内容,如果未能解决你的问题,请参考以下文章

Spring_data_jpa以及Hibernate简单使用

spring data jpa 的简单使用

Spring Data 系列 Spring+JPA(spring-data-commons)

Spring-data-jpa的简单使用

spring-data-jpa的简单使用动态sql分页排序

Spring Data JPA的简单使用