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 enhance the Design of entity objects in SpringDataJpa

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "how to enhance the design of SpringDataJpa entity objects", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "SpringDataJpa how to enhance the design of entity objects"!

Entity Enhancement plug-in first Edition requirements

In the daily Java-web development process, we often need to do some single table data operations, commonly used operations are: single table addition, single table query according to ID, single table deleted according to ID, single table modified according to ID. The basic operation of these four single tables often requires writing a lot of repetitive code. How to avoid writing repetitive code becomes a problem. In the face of such a problem, our conventional solution is code generator, which can directly get Controoler, service and dao through database table statements so as to avoid repeated writing. In addition, the author thinks about another way to do this without going through the code generator through an annotation.

Design

The first thing to consider is the API design of four single table operations. In general, the author will define several API. The following is about the new API. I will design the following interfaces.

Take users as examples to add new ones.

POST http://host:port/userContent-Type: application/json// add parameter {}

Take the department as an example to make a new example.

POST http://host:port/deptContent-Type: application/json// add parameter {}

For the above two API designs, we can see some similarities, the same is that the requests are made through POST, the difference is that the following routing address and parameters, for such two sets of interfaces can be abstracted into the following interface

New interface after abstraction

POST http://host:port/{entity_name}Content-Type: application/json// add parameter {}

The same three other operations can be abstracted in a similar way.

Query interface according to ID

GET http://host:port/{entity_name}/{id}

Modify Interfac

PUT http://host:port/{entity_name}Content-Type: application/json// modify parameter {}

Delete an interface according to ID

DELETE http://host:port/{entity_name}/{id}

The design of the basic interface is completed, and the basic Controller code can be written first.

@ RestControllerpublic class EntityPluginController {@ GetMapping ("/ {entityPluginName} / {id}") public ResponseEntity findById (@ PathVariable ("entityPluginName") String entityPluginName, @ PathVariable ("id") String id) {return null;} @ PostMapping ("/ {entityPluginName}") public ResponseEntity save (@ PathVariable ("entityPluginName") String entityPluginName, @ RequestBody Object insertParam) {return null } @ PutMapping ("/ {entityPluginName}") public ResponseEntity update (@ PathVariable ("entityPluginName") String entityPluginName, @ RequestBody Object updateParam) {return null;} @ DeleteMapping ("/ {entityPluginName} / {id}") public ResponseEntity deleteById (@ PathVariable ("entityPluginName") String entityPluginName, @ PathVariable ("id") String id) {return null;}}

In this paper, we use JPA as the data interaction layer, and JAP as the interaction will have two key objects, the first is the database entity, the second is the Repository interface. Usually, the CrudRepository interface is selected as the root object of the data interaction layer, and the JpaRepository interface is selected as the root object of the data interaction layer. There are indirect references between these two types, as shown in the class diagram below.

After learning about the commonly used JPA operators, I looked at an Entity object.

@ Entity@Table (name = "oauth_client", schema = "shands_uc_3_back", catalog = "") public class OauthClientEntity {private Long id; private String clientId; private String clientSecurity; private String redirectUri; private Long version; / / omit getter&setter}

All the actions we do in the development of a single table operate around this database entity, such as converting new parameters into database objects when adding new ones, converting update parameters into database objects when updating, and converting query results (database objects) into return objects according to ID query. there are a total of three kinds of database object conversions, which are essential. Of course, you can also use a database object to satisfy this operation directly to reduce the amount of code (not recommended). For these three transformations, first define an interface that represents the conversion process of the three objects.

Three transformations of database objects

Public interface EntityConvert {/ * convert data from insert param db entity * * @ param insType insert param * @ return db entity * / EntityType fromInsType (InsType insType); / * * convert data from update param to db entity * * @ param upType update param * @ return db entity * / EntityType fromUpType (UpType upType) / * * convert data from db entity to response entity * * @ param entityType db entity * @ return response entity * / ResType fromEntity (EntityType entityType);}

Four generics are defined in the EntityConvert interface, which means

InsType: parameter type when it is added

UpType: parameter type when modified

ResType: the parameter type when returned

EntityType: database entity type

After the interface definition is completed, you need to bind the implementation class of the interface to the entity object. The simplest binding mode is expressed by annotations, which are defined as follows.

@ java.lang.annotation.Target ({ElementType.TYPE}) @ java.lang.annotation.Retention (java.lang.annotation.RetentionPolicy.RUNTIME) @ java.lang.annotation.Documented@java.lang.annotation.Inheritedpublic @ interface EntityPlugin {/ * name * * @ return name * / String name (); / * * {@ link EntityConvert} class * @ return class * / Class self; private Class idClass;}

Name represents the name attribute of the annotated EntityPlugin

ConvertClass represents the type of EventConvert implementation class

CrudRepository represents the JPA database operation object

Self represents the entity class type

IdClass represents the ID data type of the entity class

After completing this, the problem we need to solve is how to extract classes and ID types from the JPA interface. As shown in the following code, we need to extract two generics of CrudRepository

@ Repositorypublic interface OauthClientRepo extends CrudRepository {}

You need to use reflection here. The specific operation code is as follows:

Public class InterfaceReflectUtils {private InterfaceReflectUtils () {} public static List > res = new ArrayList (); Class cur = check; while (cur! = null & & cur! = Object.class) {Type [] types = cur.getGenericInterfaces () For (Type type: types) {/ / todo: modified to infer if (type.getTypeName (). Contains (targetClass.getName () {Type [] typeArguments = ((ParameterizedType) type) .getActualTypeArguments (); for (Type typeArgument: typeArguments) {if (typeArgument instanceof Class) {res.add ((Class) typeArgument) }} break;}} Class [] interfaces = cur.getInterfaces (); if (interfaces! = null) {for (Class inter: interfaces) {List

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

Development

Wechat

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

12
Report