Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get started with SpringJPA

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to start SpringJPA, in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Start with a helloworld

After the establishment of the springboot project

Pom.xml

Org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.projectlombok lombok true com.alibaba fastjson 1.2.47 com.alibaba druid 1.0.29 mysql mysql-connector-java 8.0.11 org.springframework.boot spring-boot-starter-test test

Configuration file

Spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/jpa?useSSL=FALSE&serverTimezone=GMT%2B8username: rootpassword: roottype: com.alibaba.druid.pool.DruidDataSourcefilters: statmaxActive: 1maxWait: 60000minIdle: 1timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: select 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxOpenPreparedStatements: 20 jpa: hibernate: ddl-auto: updateshow-sql: true

Entity class

@ Entity@Data@RequiredArgsConstructor@AllArgsConstructor@NoArgsConstructorpublic class User {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Long id; @ NonNull private String name; @ NonNull private String email;}

Warehouse file

Public interface UserRepository extends CrudRepository {}

Controller

@ RestControllerpublic class UserController {@ Autowired private UserRepository userRepository; @ SuppressWarnings ("unchecked") @ Transactional @ GetMapping ("/ add") public Result addNewUser (@ RequestParam ("name") String name,@RequestParam ("email") String email) {User user = new User (name,email); userRepository.save (user); return Result.success ("add user successfully") @ GetMapping ("/ all") @ SuppressWarnings ("unchecked") public Result getAllUsers () {return Result.success (userRepository.findAll ());} @ GetMapping ("/ user") @ SuppressWarnings ("unchecked") public Result getUser (@ RequestParam ("id") Long id) {return Result.success (userRepository.findById (id));}}

You can also query it directly by name.

Public interface UserAloneRepository extends Repository {List findByName (String name);}

Add in UserController

Autowiredprivate UserAloneRepository userAloneRepository;@GetMapping ("/ user/name") @ SuppressWarnings ("unchecked") public Result getUserByName (@ RequestParam ("name") String name) {return Result.success (userAloneRepository.findByName (name));}

One of the advantages of jpa is that you don't have to build tables in the database manually, and you can create tables automatically as soon as you run them.

If you want to page and sort

Public interface UserPagingAndSortingRepository extends PagingAndSortingRepository {}

Add to Controller

/ * paging and sorting * @ return * / @ SuppressWarnings ("unchecked") @ GetMapping ("/ page") public Result getAllUserByPage () {return Result.success (new PageRequest (0mem2) new Sort (new Sort.Order (Sort.Direction.ASC, "name") } / * sort * @ return * / @ SuppressWarnings ("unchecked") @ GetMapping ("/ sort") public Result getAllUserWithSort () {return Result.success (new Sort (new Sort.Order (Sort.Direction.ASC (Sort.Direction.ASC, "name");}

Let's take a look at his overall inheritance structure diagram.

Among them, SimpleJpaRepository is the implementation class of all their interfaces, while the above JpaRepository is actually compatible with noSql, and only the following JpaRepository is the unique interface to the database.

The same method is used, which only needs to be inherited by a custom interface.

Public interface UserJpaRespository extends JpaRepository {}

Jpa has its own query builder mechanism based on the method name. For example, findByName,findBy in the previous UserAloneRepository is a fixed prefix, and Name is the property name. Let's take a look at some queries about and and or.

Public interface UserAloneRepository extends Repository {List findByName (String name); List findByNameAndEmail (String name,String email); List findByNameOrEmail (String name,String email);}

In Controller

SuppressWarnings ("unchecked") @ GetMapping ("/ and") public Result getUserByNameAndEmail (@ RequestParam ("name") String name,@RequestParam ("email") String email) {return Result.success (userAloneRepository.findByNameAndEmail (name,email));} @ SuppressWarnings ("unchecked") @ GetMapping ("/ or") public Result getUserByNameOrEmail (@ RequestParam ("name") String name,@RequestParam ("email") String email) {return Result.success (userAloneRepository.findByNameOrEmail (name,email));}

We can see from the printed log

Hibernate: select user0_.id as id1_0_, user0_.email as email2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? And user0_.email=?

Hibernate: select user0_.id as id1_0_, user0_.email as email2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? Or user0_.email=?

In fact, it is and and or after the where statement.

This kind of and and or are multi-conditional queries that can be followed indefinitely. Now let's take a look at the weight and take the first few data.

Public interface UserAloneRepository extends Repository {List findByName (String name); List findByNameAndEmail (String name,String email); List findByNameOrEmail (String name,String email); / / deduplicated List findDistinctByName (String name); / / find the first 2 List findTop2ByName (String name);}

Just add the Distinct and Top numbers.

Now add two fields to the User entity class

@ Entity@Data@RequiredArgsConstructor@AllArgsConstructor@NoArgsConstructorpublic class User {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Long id; @ NonNull private String name; @ NonNull private String email; private int age; private boolean sex;}

When you start the project, the database automatically adds this field to the user table

All the jpa keywords are as follows

Public interface UserAloneRepository extends Repository {List findByName (String name); List findByNameAndEmail (String name,String email); List findByNameOrEmail (String name,String email); / / deduplicated List findDistinctByName (String name); / / find the first two List findTop2ByName (String name); / / find List findByAgeBefore (int age) less than the age parameter; / / find List findByAgeLessThan (int age) less than the age parameter / find List findByAgeLessThanEqual (int age) less than or equal to age parameter; / / find List findByAgeAfter (int age) greater than age parameter; / / find List findByAgeGreaterThan (int age) greater than age parameter; / / find List findByAgeGreaterThanEqual (int age) greater than or equal to age parameter; / / find List findByNameIsNull () whose name is null; / / find List findByNameNotNull () whose name is not null / find like name (without%) List findByNameLike (String name); / find not like name (without%) List findByNameNotLike (String name); / find like% name (no suffix%) List findByNameStartingWith (String name); / find like name% (no prefix%) List findByNameEndingWith (String name); / find like% name% List findByNameContaining (String name) / / sort List findByNameOrderByAgeDesc (String name) by age according to name search; / / find List findByAgeNot (int age) that is not equal to age; / / find List findByAgeIn (Set ages) in the ages collection according to age; / / find List findByAgeNotIn (Set ages) that is not in the ages collection according to age; / / find List findBySexTrue () with sex 1; / find List findBySexFalse () with sex 0 / / search by email, case-insensitive List findByEmailIgnoreCase (String email); / find the total number of long countByName by name (String name); / / delete by name / / here is deleted according to the found id, so you must add transaction long deleteByName (String name) when calling. / / delete according to name / / here is deleted one by one according to the found id, so transaction List removeByName (String name) must be added when calling.

You must bring the transaction with you when deleting

@ Transactional@SuppressWarnings ("unchecked") @ GetMapping ("/ delete") public Result deleteByName (@ RequestParam ("name") String name) {userAloneRepository.deleteByName (name); return Result.success ("deleted successfully");} @ Transactional@SuppressWarnings ("unchecked") @ GetMapping ("/ remove") public Result removeByName (@ RequestParam ("name") String name) {return Result.success (userAloneRepository.removeByName (name);}

According to the printed log, you can see that it was actually deleted according to id.

Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.email as email3_0_, user0_.name as name4_0_, user0_.sex as sex5_0_ from user user0_ where user0_.name=?

Hibernate: delete from user where id=?

Hibernate: delete from user where id=?

This is the end of the answer to the question on how to get started with SpringJPA. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report