In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge points of Spring JPA use case analysis. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
1. What is JPA?
JPA (Java Persistence API) is an official Java persistence specification proposed by Sun. It provides Java developers with an object / association mapping tool to manage relational data in Java applications. The main purpose of his appearance is to simplify the existing persistence development work and integrate ORM technology, and put an end to the current messy situation of ORM frameworks such as Hibernate,TopLink,JDO. JPA is developed on the basis of fully absorbing the existing Hibernate,TopLink,JDO and other ORM frameworks, and has the advantages of easy to use, strong scalability and so on. From the above explanation, we can see that JPA is a set of specifications, while products like Hibernate,TopLink,JDO implement the JPA specification.
Now that we know what JPA is, let's take a look at the protagonist of this article, spring data jpa.
2.spring data jpa
Pring Data JPA is a set of JPA application framework encapsulated by Spring based on ORM framework and JPA specification. The bottom layer is implemented by JPA technology of Hibernate, which enables developers to access and operate data with minimal code. It provides common functions including additions, deletions, modifications and searches, and is easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency.
What do you mean? If you have used Hibernate or MyBatis, you will know how convenient the object-relational mapping (ORM) framework is. But the Spring Data JPA framework goes a step further, doing almost anything that a data persistence layer framework can do. Take Springboot integrating MyBatis as an example. For example, if we want to insert some user's data into the database, we need to define the user's entity class first, and then we need to define a UserDao:
@ Repositorypublic class UserDao {@ Autowired JdbcTemplate jdbcTemplate; public int addUser (User user) {return jdbcTemplate.update ("INSERT INTO t_user (username,jobs,phone) VALUE (?,?), user.getName,user.getJobs,user.getPhone);} public int updateUser (User user) {return jdbcTemplate.update (" UPDATE t_user SET username=?,jobs=?,phone=?) WHERE id=? ", user.getName,user.getJobs,user.getPhone,user.getId);} public int deleteUser (Integer id) {return jdbcTemplate.update (" DELETE FROM t_user WHERE id=? ", id);} public User getUserById (Integer id) {return jdbcTemplate.queryForObject (" SELECT * FROM t_user WHERE id=? ", new BeanPropertyRowMapper (User.class), id) } public List getAllUser {return jdbcTemplate.query ("SELECT * FROM t_user", new BeanPropertyRowMapper (User.class));}}
And UserService.
@ Servicepublic class UserService {@ Autowired UserDao userDao; public int addUser (User user) {return userDao.addUser (user);} public int updateUser (User user) {return userDao.updateUser (user);} public int deleteUser (Integer id) {return userDao.deleteUser (id);} public User getUserById (Integer id) {return userDao.getUserById (id);} public List getAllUser {return userDao.getAllUser;}}
Finally, we are going to call the method in the corresponding service. This is the traditional way, if you use mapper, it will be a little easier, for example, we want to add mapper
@ Mapperpublic interface UserMapper {int addUser (User user); int deleteUser (int id); int updateUser (User user); User getUserById (Integer id); List getAllUsers;}
Then define a UserMapper.xml, add the corresponding CURD SQL statement, do the mapping, and then modify the service, such as
@ Servicepublic class UserService {@ Autowired UserMapper userMapper; public int addUser (User user) {return userMapper.addUser (user);} public int updateUser (User user) {return userMapper.updateUser (user);} public int deleteUser (Integer id) {return userMapper.deleteUser (id);} public User getUserById (Integer id) {return userMapper.getUserById (id);} public List getAllUser {return userMapper.getAllUsers;}}
Did you find anything wrong? If we are going to implement the operation of multiple tables, we need to define different entity classes, then implement the corresponding mapper, then write the same addition, deletion, modification and search method, and finally call it. This is too troublesome, and Spring data jpa can easily help us achieve these tedious, repetitive and untechnical operations. Let's take a look!
3. Case demonstration
1. First, we need to configure pom.xml
Mysql mysql-connector-java org.springframework.boot spring-boot-starter-data-jpa
two。 Then there is the configuration of application.properties
Spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=truespring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.jpa.properties.hibernate.hbm2ddl.auto=createspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialectspring.jpa.show-sql=true
Here is a brief introduction to the several configurations of spring.jpa.properties.hibernate.hbm2ddl.auto:
Create: means that the last generated table (including data) is deleted each time Hibernate is loaded, and then the new table is regenerated, even if there are no changes twice. It is suitable for scenarios where the database is emptied before each single test is performed.
Create-drop: indicates that a table is generated each time Hibernate is loaded, but when SessionFactory is closed, the generated table is automatically deleted.
Update: the most commonly used attribute value. A data table is created when Hibernate is loaded for the first time (as long as a database is required). When Hibernate is loaded later, the last generated table will not be deleted. It will be updated according to the entity, only new fields will be added, and fields will not be deleted (even if they have been deleted in the entity).
Validate: each time Hibernate is loaded, the data table structure is validated, only compared with existing data tables, and the table structure is modified according to model, but no new table is created.
If this item is not configured, the automatic table creation feature is disabled.
Spring.jpa.show-sql=true this configuration prints sql statements on the console when performing database operations, making it convenient for us to check for troubleshooting and so on.
Spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect this is the dialect configuration of the database.
3. Next, let's build the user entity class.
@ Entitypublic class User {@ Id @ GeneratedValue private long id; @ Column (nullable = false, unique = true) private String userName; @ Column (nullable = false) private String password; @ Column (nullable = false) private int age;}
Some of the notes here are explained as follows:
@ Entity is a class annotation used to note that this class is an entity class used to associate with tables in the database. When you start a project for the first time, a table (table) with the same name as the entity class is generated in the data by default. You can also modify the name of the table (table) through the name attribute in the annotation, such as @ Entity (name= "user"), so that the name of the table in the database is user. This annotation is very important, without which you will find that the database does not generate the corresponding table when you start the project for the first time.
The @ Table annotation is also a class annotation, which can be used to modify the name of the table. The annotation can be ignored. The @ Entity annotation already has the function of the annotation.
The property annotation of the @ Id class, which indicates that the property field is a primary key and that the property must have and is indispensable.
@ GeneratedValue this annotation is usually used in conjunction with the @ Id primary key annotation to define the presentation of the primary key. This annotation usually has a variety of strategies, which can be summarized as follows:
@ GeneratedValue (strategy= GenerationType.IDENTITY) this annotation is automatically generated by the database and is self-increasing in the primary key. It is most frequently used in mysql databases and is not supported by oracle.
The @ GeneratedValue (strategy= GenerationType.AUTO) primary key is controlled by the program. The default primary key generation policy is serialization for oracle and self-increasing primary key for mysql.
@ GeneratedValue (strategy= GenerationType.SEQUENCE) generates the primary key based on the sequence of the underlying database, provided that the database supports the sequence, Oracle supports it, and Mysql does not.
@ GeneratedValue (strategy= GenerationType.TABLE) uses a specific database table to hold the primary key, which is rarely used.
Among the above primary key generation strategies, take mysql as an example, IDENTITY and AUTO are more commonly used, and IDENTIT is more used in both. The demo primary key demonstrated in the following article uses the @ GeneratedValue (strategy= GenerationType.IDENTITY) generation strategy.
@ Column is a class attribute annotation that defines the specific characteristics of a field mapped to a database property, such as the field length, the specific name of the attribute when it is mapped to the database, and so on.
@ Transient is an attribute annotation whose fields are not mapped to the database.
4. Declare the UserRepository interface, inheriting JpaRepository, as follows
Public interface UserRepository extends JpaRepository {}
The JpaRepository here inherits the interfaces PagingAndSortingRepository and QueryByExampleExecutor. PagingAndSortingRepository, in turn, inherits CrudRepository.
Therefore, the JpaRepository interface has both basic CRUD functions and paging functions. Therefore, here we can inherit JpaRepository to obtain a variety of basic data manipulation methods that Spring defines for us in advance.
5. Then we define a test class, and here we demonstrate the add operation, @ Transactional means to open the transaction to prevent dirty data.
…… @ Autowired private UserRepository userRepository; @ Test @ Transactional public void userAddTest () {User user = new User (); user.setUserName ("Daniel Wu"); user.setAge (30); user.setPassword ("123456"); userRepository.save (user); User item = userRepository.findByUserName ("wyk"); log.info (JsonUtils.toJson (item));}
6. Next, we talk about query, query can be divided into basic query and custom query, one is that spring data has been implemented by default, only need to inherit JpaRepository, and the other is to automatically parse into SQL according to the query method.
@ Testpublic void testQuery () throws Exception {User user=new User (); userRepository.findAll (); userRepository.findOne (1l); userRepository.save (user); userRepository.delete (user); userRepository.count (); userRepository.exists (11); … }
7. A custom simple query automatically generates SQL based on the method name. The main syntax is findXXBy,readAXXBy,queryXXBy,countXXBy, and getXXBy is followed by the attribute name, to name a few examples:
User findByUserName (String userName); User findByUserNameOrEmail (String username, String email); Long deleteById (Long id); Long countByUserName (String userName); List findByEmailLike (String email); User findByUserNameIgnoreCase (String userName); List findByUserNameOrderByEmailDesc (String email)
8. Next, let's talk about complex queries. In actual development, we need special methods or custom SQL when we need to use queries such as paging, deleting, and joining tables. Take paging query as an example, paging query is very common in practice. Spring data jpa has helped us to achieve the function of paging. In the query method, we need to input the parameter Pageable. When there are multiple parameters in the query, Pageable recommends that you pass in as the last parameter. Pageable is a paging implementation class encapsulated by spring. When you use it, you need to pass in the number of pages, pages per page, and sorting rules.
Page findALL (Pageable pageable); Page findByUserName (String userName,Pageable pageable)
9. Let's take a look at the following test cases
Testpublic void testPageQuery () throws Exception {int page=1,size=5; Sort sort = new Sort (Direction.DESC, "id"); Pageable pageable = new PageRequest (page, size, sort); userRepository.findALL (pageable); userRepository.findByUserName ("testName", pageable);}
Most of Spring data's SQL can be implemented according to the method name definition, but for some reason we want to use custom SQL to query, spring data is also perfectly supported, as shown below:
@ Modifying@Query ("update User u set u.userName =? 1 where c.id =? 2") int modifyByIdAndUserId (String userName, Long id); @ Transactional@Modifying@Query ("delete from User where id =? 1") void deleteByUserId (Long id); @ Transactional (timeout = 10) @ Query ("select u from User u where u.emailAddress =? 1") User findByEmailAddress (String emailAddress). That's all of the Spring JPA use case study article. Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.