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

What does AbstractEntity need to prepare?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what do you need to prepare for AbstractEntity". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what AbstractEntity needs to prepare.

Relational databases can be annoying, especially when you use a database-driven development model. You need to first create the table, and then use the code generator to reverse generate a pile of code that is almost unreadable. When there is a change in the field, there is another toss-up.

A typical example of this is MyBatis, which leads to a more concise MyBatis Plus.

Knowing some big factories (Ali, Tencent, Douyin, etc.), the use of JPA is becoming more and more widespread, including our company, which puts the right tools in the right place. If you want to develop quickly, JPA is undoubtedly a better choice. You don't need to pay attention to the structure of the database table, you can use a code driver to get the job done, whether it's MySQL or Oracle. JPA weakens database-related knowledge and allows you to focus on business development.

Personally, I used to reject JPA as a tool that weakens SQL, which stems from a misunderstanding of the early version of Hibernate. But after trying mybatis, spring-data-jdbc and jooq, I found that this thing is really fragrant! A late like, sent to JPA.

This is very suitable for some management systems. Because performance is not the main pain point for these systems, business complexity is.

This article will introduce a simple entity class and what basic fields you need to prepare. And how these fields are used in the code.

1. Basic field introduction

First take a look at our basic definition class.

There is not much code, but a lot of information.

Let's parse line by line.

@ Data

Data annotations belong to the lombok class. Lombok is a well-known code simplification tool that provides a lot of annotations. If you don't want to remember too many comments, adding a Data directly is the laziest choice.

@ MappedSuperclass

This annotation is JPA and is used to identify the parent class. The class labeled @ MappedSuperclass will not be a complete entity class and will not be mapped to the database table, but its properties will be mapped to the database fields of the subclass. This is the perfect place to put it.

@ EntityListeners (AuditingEntityListener.class)

Turn on the automatic audit function, which is compatible with the two date fields below, which we will describe later.

@ JsonIgnoreProperties (value = {"hibernateLazyInitializer", "handler"}) / / avoid json serial number failure when using bean directly

Sometimes we want entities that use JPA directly in the controller layer. But there are a lot of additional variables inside JPA, such as hibernateLazyInitializer.

In order for the entity to work properly during json serialization, these two fields need to be ignored. So this comment belongs to jackson json.

two。 Custom ID Generator

JPA actually provides a lot of ID generation strategies. However, in Internet applications, snowflake algorithm is more widely used, because it has good scalability and there will not be many conflicts during data migration.

To specify the snowflake algorithm, we need the following lines of code.

Static final String ID_GEN = "cn.xjjdog.bcmall.utils.db.DistributedId"; @ Id @ GenericGenerator (name = "IdGen", strategy = ID_GEN) @ GeneratedValue (generator = "IdGen")

One of the keys is to use the ID generator we call IdGen. The code here is a bit of a pity. Because the JVM class is loaded, we cannot directly use the name of the class (* .class.getName ()) in the annotation to get its package path, we can only write it here as a string.

Let's take a look at the processing of this ID generator.

Public class DistributedId implements IdentifierGenerator {@ Override public Serializable generate (SharedSessionContractImplementor sharedSessionContractImplementor, Object obj) throws HibernateException {if (obj = = null) throw new HibernateException (new NullPointerException ()); if (AbstractEntity) obj). GetId () = = null) {return String.valueOf (Snowflake.createId ());} else {return ((AbstractEntity) obj). GetId ();}

The code is as above. We also did a little bit of processing before using it directly. When we determine that the ID of the entity is empty, we use the snowflake algorithm to construct a new ID;, otherwise the ID that the entity has been set up will remain unchanged.

Why would you do that? Because there is a need for it. In a business like an order, you need to make an order number, then update some database information, publish some messages, etc., instead of generating one when the save action starts.

If you don't do the above code processing. JPA will automatically generate one each time it is saved, overwriting your original one. This is where I lost money and fixed it through debug code.

3. Automatically populate the field

The above mentioned createdDate and lastModifiedDate fields, in fact, when using, do not need to manually set the value. These two values will be completed automatically through the audit function.

@ EntityListeners (AuditingEntityListener.class)

Of course, we also use unique annotations to identify these two fields.

/ * creation time * / @ CreatedDate private Date createdDate; / * Update time * / @ LastModifiedDate private Date lastModifiedDate

Finally, don't forget to turn on this feature through Config in the global configuration.

@ Configuration @ EnableJpaAuditing public class JpaConfig {}

Of course, auditing cannot be done without users. So the series also has @ CreatedBy annotations to mark who created it. You need to assemble them in code, such as the following code, to get user information from Spring Sercurity.

@ Configuration @ Slf4j public class UserAuditor implements AuditorAware {@ Override public Optional getCurrentAuditor () {UserDetails user; try {user = (UserDetails) SecurityContextHolder.getContext () .getAuthentication () .getPrincipal (); return Optional.ofNullable (user.getUsername ());} catch (Exception e) {return Optional.empty ();}

4. End

JPA write management system, is really an artifact. It's a very good choice when you don't need to think about the ultimate code efficiency. If you look at the recent MyBatis version, including the MyBatis Plus design, a lot of things are becoming more and more like JPA. Because in terms of design, JPA is closest to the idea of object-oriented programming.

The technology stack of B-side complex business does not need to be the same as that of C-side. JPA obviously gets things done with very little code and conventions, allowing developers to really focus on business development. In later articles, we will also use MyBatis and MyBatis Plus, and then we will analyze the scenarios they use in detail.

At this point, I believe you have a deeper understanding of "what AbstractEntity needs to prepare". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Database

Wechat

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

12
Report