In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to use delete in SpringBoot JPA". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
There are four common operations of curd in db. The previous blog posts introduced insert,update respectively. Next, let's take a look at the posture of delete and how to delete data through JPA.
Generally speaking, it is not recommended to physically delete (delete records directly from the table) data. in today's era when data is money, it is more common to add a field to the table that represents the status. Then modify this field to indicate whether the record is valid, so as to achieve logical deletion; the reasons for this are as follows
Physical deletion. If something goes wrong, it will be troublesome to recover.
There is no guarantee that the code will be accurate. If you delete the wrong data when something goes wrong, you will gg.
Deleting data will cause the index to be rebuilt
The Innodb database only marks the deleted data as deleted, and does not really release the disk space occupied, which leads to the continuous growth of InnoDB database files and table fragmentation.
Logical deletion and retention of data to facilitate subsequent data mining or analysis
i. Environmental preparation
Before you start, of course, you have to prepare the basic environment, such as installing and testing using mysql, creating a SpringBoot project project, setting up configuration information, etc. For more information on building a project, please refer to the previous article.
Building the basic environment of 190612-SpringBoot series tutorials JPA
Let's briefly take a look at the configuration needed to demonstrate the process of adding records.
1. Table preparation
Follow the table of the previous article, with the following structure
CREATE TABLE `money` (`id` int (11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar (20) NOT NULL DEFAULT''COMMENT' username', `money`int (26) NOT NULL DEFAULT'0' COMMENT 'money', `is_ deleted`tinyint (1) NOT NULL DEFAULT '0percent, `create_ at`timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT' creation time, `update_ at`update time', PRIMARY KEY (`id`), KEY `name` (`name`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 two。 Project configuration
Configuration information, which is slightly different from that before, we have added more detailed log printing. The main goal of this article is to add the usage posture of records. For the configuration instructions, we will explain them separately later.
# # DataSourcespring.datasource.url=jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=falsespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.username=rootspring.datasource.password=## jpa-related configuration spring.jpa.database=MYSQLspring.jpa.hibernate.ddl-auto=nonespring.jpa.show-sql=truespring.jackson.serialization.indent_output=truespring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl3. Data preparation
Data modification, so let's first insert two pieces of data into the table for later operations.
INSERT INTO `money` (`id`, `name`, `money`, `is_ deleted`, `jpa at`, `money`) VALUES (20, 'jpa one grey 5mm, 2323, 0,' 2019-07-02 081lv 41mm, '2019-07-02 08lv 42lv 41'), (21,' jpa one gray 6mm, 2333, 0, '2019-07-02 082purr 41mm,' 2019-07-02 08create_ 42pur41'), (22) 'jpa one Gray 7, 6666, 0,' 2019-07-02 08Gray 42rig 41mm, '2019-07-02 08VO 42v 41'), (23,' jpa one Gray 8mm, 2666, 0, '2019-07-02 08V 42v 41L,' 2019-07-02 08Rd 42v 41')
II. Delete usage tutorials
The deletions mentioned below are all physical deletions, which can be understood as directly erasing some records from the table (not that there is no way to restore them if deleted) for the four operations of CURD, except read, the other three insert,update,delete will add write locks (generally, row locks and gap locks will be involved, as you will see later, these three operations require the declaration to be displayed)
1. Table association POJO
The previous insert has introduced the step-by-step creation process of POJO and the corresponding annotation meaning. The results are posted directly below.
@ Data@DynamicUpdate@DynamicInsert@Entity@Table (name = "money") public class MoneyPO {@ Id / / if it is auto, the exception Table 'mysql.hibernate_sequence' doesn't exist / / @ GeneratedValue (strategy = GenerationType.AUTO) @ GeneratedValue (strategy = GenerationType.IDENTITY) @ Column (name = "id") private Integer id; @ Column (name = "name") private String name; @ Column (name = "money") private Long money will be reported @ Column (name = "is_deleted") private Byte isDeleted; @ Column (name = "create_at") @ CreatedDate private Timestamp createAt; @ Column (name = "update_at") @ CreatedDate private Timestamp updateAt;}
Several comments in the above class are described as follows
@ Data belongs to lombok annotations, has nothing to do with jpa, and automatically generates getter/setter/equals/hashcode/tostring and other methods
@ Entity, @ Table jpa annotation, indicating that this class is associated with the table of db, which matches the table money
@ Id @ GeneratedValue function and self-increasing primary key
@ Column indicates that this property corresponds to a column in the table
@ CreateDate generates a default timestamp based on the current time
2. Repository API statement
Next, we create a new api that inherits from CurdRepository, and then use this api to deal with the database.
Public interface MoneyDeleteRepository extends CrudRepository {/ * query test * @ param id * @ return * / List queryByIdGreaterThanEqual (int id);} 3. Use posture
First write a method for querying the data to verify whether it was actually deleted after we performed the deletion
Private void showLeft () {List records = moneyDeleteRepository.queryByIdGreaterThanEqual (20); System.out.println (records);}
Before performing the following operations, call the above, and the output is as follows
[MoneyPO (id=20, name=jpa one Gray 5, money=2323, isDeleted=0, createAt=2019-07-02 08Gray 42Rover 41.0, updateAt=2019-07-02 08RV 42RV 41.0), MoneyPO (id=21, name=jpa one Gray 6, money=2333, isDeleted=0, createAt=2019-07-02 08RU 42RV 41.0, updateAt=2019-07-02 08RU 42RV 41.0), MoneyPO (id=22, name=jpa one Gray 7, money=6666, isDeleted=0, createAt=2019-07-02 08RU 42pur41.0, updateAt=2019-07-02 08Rue 42pur41.0), MoneyPO (id=23-07-02 08R 42RU 41.0) Name=jpa Gray 8, money=2666, isDeleted=0, createAt=2019-07-02 08 createAt=2019-07-02 08 isDeleted=0 41.0, updateAt=2019-07-02 08 isDeleted=0 41.0)] a. Delete according to the primary key id
This should be the most common way to delete, in order to avoid erroneous deletion, it is a very good posture to delete records through the precise primary key id. CrudRepository this interface already provides the corresponding method, so we can directly use the
Private void deleteById () {/ / delete moneyDeleteRepository.deleteById (21); showLeft ();} directly according to id
After the execution is completed, the output result is as follows. Compared with the previous output, you can see that the record of id=21 has been deleted.
[MoneyPO (id=20, name=jpa one Gray 5, money=2323, isDeleted=0, createAt=2019-07-02 08VZ 42RV 41.0, updateAt=2019-07-02 08RV 42RU 41.0), MoneyPO (id=22, name=jpa one Gray 7, money=6666, isDeleted=0, createAt=2019-07-02 08RU 42RV 41.0, updateAt=2019-07-02 08RU 42RV 41.0), MoneyPO (id=23, name=jpa one Gray 8, money=2666, isDeleted=0, createAt=2019-07-02 08UR 42RU 41.0, updateAt=2019-07-02 08Rue 42RU 41.0)]
Then a question comes naturally, what if the corresponding record for this id does not exist?
Execute the above code again and find that an exception has been thrown
What causes it? When we enter debug, the implementation of the call is the default SimpleJpaRepository, and its source code is as follows
/ / classes are: org.springframework.data.jpa.repository.support.SimpleJpaRepository@Transactionalpublic void deleteById (ID id) {Assert.notNull (id, ID_MUST_NOT_BE_NULL); delete (findById (id). OrElseThrow (()-> new EmptyResultDataAccessException ("No% s entity with id% s exists!", entityInformation.getJavaType (), id), 1) } @ Transactionalpublic void delete (T entity) {Assert.notNull (entity, "The entity must not be null!"); em.remove (em.contains (entity)? Entity: em.merge (entity));}
As can be seen from the source code, this is first queried through id, and if the corresponding record does not exist, an exception is thrown directly; when it does, follow the remove logic
What can we do if we want to delete a non-existent data without reporting an error?
Custom implement a class that inherits SimpleJpaRepository and overrides the delete method
@ Repository@Transactional (readOnly = true) public class MoneyDeleteRepositoryV2 extends SimpleJpaRepository {@ Autowired public MoneyDeleteRepositoryV2 (EntityManager em) {this (JpaEntityInformationSupport.getEntityInformation (MoneyPO.class, em), em);} public MoneyDeleteRepositoryV2 (JpaEntityInformation entityInformation, EntityManager entityManager) {super (entityInformation, entityManager);} public MoneyDeleteRepositoryV2 (Class domainClass, EntityManager em) {super (domainClass, em);} @ Override public void deleteById (Integer id) {Optional rec = findById (id) Rec.ifPresent (super::delete);}}
Then call the above method on it, instead of demonstrating the specific test case, the source code can be checked in the project project. Source code
b. Conditional judgment deletion
Although it is safe to delete according to id, it is inevitable to delete according to other fields in some cases. For example, if we want to delete data named jpa-Grey 7, we need to add a new method in MoneyDeleteRepository.
/ * * delete according to name * * @ param name * / void deleteByName (String name)
Here is a relatively simple mention of the naming rules of this method, which will be explained in more detail in the query section.
Delete indicates that you are performing a delete operation
By means to qualify according to a field.
Name has the attribute matching in POJO.
The above method, if translated into sql, is equivalent to delete from money where name=xx.
The method of calling is the same as before, as follows
Private void deleteByName () {moneyDeleteRepository.deleteByName ("jpa-Grey 7"); showLeft ();}
Then we performed the above test and found that it was not successful and reported an error.
Through the previous study of update, we know that we need to display and add a note to the thing, which we add directly to the Repository here.
/ * * delete according to name * * @ param name * / @ Transactionalvoid deleteByName (String name)
Then execute the output again as follows, here we print the sql log as well
Hibernate: select moneypo0_.id as id1_0_, moneypo0_.create_at as create_a2_0_, moneypo0_.is_deleted as is_delet3_0_, moneypo0_.money as money4_0_, moneypo0_.name as name5_0_, moneypo0_.update_at as update_a6_0_ from money moneypo0_ where moneypo0_.name=?Hibernate: delete from money where id=?Hibernate: select moneypo0_.id as id1_0_, moneypo0_.create_at as create_a2_0_ Moneypo0_.is_deleted as is_delet3_0_, moneypo0_.money as money4_0_, moneypo0_.name as name5_0_, moneypo0_.update_at as update_a6_0_ from money moneypo0_ where moneypo0_.id > =? [MoneyPO (id=20, name=jpa-Gray 5, money=2323, isDeleted=0, createAt=2019-07-02 08 Vol. 41.0, updateAt=2019-07-02 08-R 41.0), MoneyPO (id=23, name=jpa-Gray 8, money=2666, isDeleted=0, createAt=2019-07-02 08 V 441.0) UpdateAt=2019-07-02 08 42purl 41.0)]
From the final remaining records, name is jpa one gray 7 has been deleted, and then take a look at the previous deletion of sql, you will find an interesting place, deleteByName this method, translated into sql into two
Select * from money where name=xxx first query records based on name
Delete from money where id = xxx deletes the record based on the id of the previous query record
c. Compare deletion
Next, we will show you how to delete the record of money in the range of [2000, 553, 000]. At this time, our new entry can be
/ * * delete * * @ param low * @ param big * / @ Transactionalvoid deleteByMoneyBetween (Long low, Long big) based on number comparison
You can also simply know that the above is equivalent to sql delete from money where money between xxx and xxx by naming the method.
The test code is
Private void deleteByCompare () {moneyDeleteRepository.deleteByMoneyBetween (2000L, 3000L); showLeft ();}
Output log
Hibernate: select moneypo0_.id as id1_0_, moneypo0_.create_at as create_a2_0_, moneypo0_.is_deleted as is_delet3_0_, moneypo0_.money as money4_0_, moneypo0_.name as name5_0_, moneypo0_.update_at as update_a6_0_ from money moneypo0_ where moneypo0_.money between? And? Hibernate: delete from money where id=?Hibernate: delete from money where id=?Hibernate: select moneypo0_.id as id1_0_, moneypo0_.create_at as create_a2_0_, moneypo0_.is_deleted as is_delet3_0_, moneypo0_.money as money4_0_, moneypo0_.name as name5_0_, moneypo0_.update_at as update_a6_0_ from money moneypo0_ where moneypo0_.id > =? []
As can be seen from the spliced sql, the above logic is equivalent to executing the query first and then deleting it one by one according to the id.
4. Summary
We implement conditional deletion by declaring methods; we need to pay attention to
Delete requires a declaration to be displayed @ Transactional
Deleting a record that does not exist will throw an exception
When you declare the deletion method, it is actually equivalent to querying the record first, and then deleting it precisely according to the id of the record.
This is the end of the content of "how to use delete in SpringBoot JPA". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.