In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use SpringBoot-JPA for custom saving and batch saving, which is very detailed and has a certain reference value. Friends who are interested must finish reading it!
Description
SpringBoot version: 2.1.4.RELEASE
Java version: 1.8
The JPA mentioned in the article all refers to spring-boot-starter-data-jpa
Save a Student object using JPA
Save an object in JPA, only that object, a repository can be done. StudentDO entity class:
Getter@Setter@Entity@Table (name = "t_student") public class StudentDO {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) @ Column private Long id; @ Column private String seq; @ Column private String name; @ Column private int sex;}
JPA warehousing:
@ Repositorypublic interface StudentRepo extends JpaRepository {}
In general, we only need to call the StudentRepo.save () method to save the entity object.
Test public void testSave () {StudentDO student = new StudentDO (); student.setName ("Zhang San"); student.setSex (1); student.setSeq ("123456"); studentRepo.save (student); Assert.assertNotNull (student.getId ());}
Use the mysql function during insertion
What if we want the seq value of student to be automatically generated by the system and the generation rule is "yyMMdd + 8-bit self-increasing sequence" (for example, 19060310000000)?
The first thing that comes to mind is how to generate this sequence. Mysql does not support sequence like oracle itself, so here you can borrow functions and additional sequence tables to achieve this operation. There are many ways to achieve this on the Internet, so I will not repeat them here.
Now that you have the function getseq ('student_seq') to get the sequence, how do you apply it to the method of saving the object? One obvious problem is that it no longer works to call the save method directly as above, and you should need a custom inserted sql implementation.
One easy way to think of is to use the annotation @ SQLInsert on the StudentDO class to define the implementation of insert, which should look like this:
@ SQLInsert (sql = "INSERT INTO t_student (seq, name, sex) VALUES (getseq ('student_seq'),??")
There is nothing wrong with the sql statement itself, and it does work when you call the save () method again. Unfortunately, it does throw a sql exception:
Java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2).
Obviously, there must be as many parameters as the program thinks. To match it, I have not found a solution to this problem at present, so this method has failed.
Since @ SQLInsert doesn't work, you might consider using the @ Query annotation to customize an implementation. We can define such a method in StudentRepo:
Transactional @ Modifying @ Query (value = "INSERT INTO t_student (seq, name, sex) VALUES (getseq ('student_seq'),: # {# student.name},: # {# student.sex})", nativeQuery = true) int insert (@ Param ("student") StudentDO student)
Try to run it, the result is very successful, the object is stored in the database normally, and the value of seq is also normal. It seems that our problem has been solved, but is this really the case?
Customized bulk Stora
In the above example, we successfully called the mysql function through JPA to store the object in the database. But the above example only provides a single save method, what if we want to save it in batches? Can the sql in @ Query be modified? I didn't find the insert method in @ Query that takes List as a parameter, but that doesn't mean it can't be performed. JPA still provides the user with the original way of using EntityManager to construct the sql and execute it.
@ PersistenceContext private EntityManager entityManager; private int batchInsert (List students) {StringBuilder sb = new StringBuilder (); sb.append ("INSERT INTO t_student (seq, name, sex) VALUES"); for (StudentDO student: students) {sb.append ("(getseq ('student_seq'),?),");} String sql = sb.toString (). Substring (0, sb.length ()-1); Query query = entityManager.createNativeQuery (sql); int paramIndex = 1 For (StudentDO student: students) {query.setParameter (paramIndex++, student.getName ()); query.setParameter (paramIndex++, student.getSex ());} return query.executeUpdate ();}
Just like MyBatis, users can also customize SQL to execute, try it, there is no problem, no matter how much data can be saved to the database! The effect of batch preservation has been achieved.
Think about it again, through the above process, is there any problem? Compared to the save () method that comes with JPA, it seems that all our custom saves return are int results, that is, the number of database rows affected by the operation. Anyone who has used JPA should know that the objects returned by JPA's save () method (or other JPA methods) are persisted, and thanks to this feature, users can get values such as the object's id that must be inserted into the database after calling the save () method. Obviously, the operation here has lost this feature, so can we do it if we change the corresponding return value to Object or List? The answer is no, we will get the following exception:
Org.springframework.dao.InvalidDataAccessApiUsageException: Modifying queries can only use void or int/Integer as return typewriter; nested exception is java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!
Insert methods must be annotated with @ Modifying, while @ Modifying annotated methods can only return results of type int. In this case, you may have to use the query to get the value of seq before you operate.
The above is all the contents of the article "how to use SpringBoot-JPA for custom saving and batch saving". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow 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.