Tool inner layer
Util: Tools
The Util layer is used to store tool classes. Small functions with high independence or code segments with high repeatability can be extracted into the Util layer
Data layer
pojo: normal java object
po: persistence layer, java objects mapped to tables in the database
vo: object of data transfer between business layers
pojo: a simple and irregular java object with only attribute + get+set+toString methods
Common notes:
@TableName("Table name") //Implement the mapping of objects and representations @Data //Implement the get/set/toString method @TableId(type = IdType.AUTO) //Set primary key auto increment @TableField("name") //Mapping of attributes to fields @TableField(exist = false) //Indicates that the current attribute is not a database field, but must be used in the project. In this way, it is added, etc //When using bean s, mybatis plus will ignore this and will not report an error
Entity: entity
Strictly corresponding to the database, the class in the entity package will have any field in the database
model: model
Generally, there is an entity class model, which is used for the back end
view: view
Generally, the mapping class (view) of the entity class table stored in it is used for the front end
Data access layer
DAO layer: mainly for the operation of data tables. It can be understood that a data table has a DAO layer corresponding to the finger
Mapper layer: mapper layer = dao layer. If the mybatis framework is used, the generated class name is mapper, which is actually dao layer.
Business layer
Service: Interface
Because Dao stores the methods for table operation, the entity class stores the POJO class of the mapping table.
The function of Service is to integrate Dao and entity classes, encapsulate them again, and encapsulate them into a method. We call this method to realize the addition, deletion, modification and query of a table.
ServiceIpml: interface implementation class
Implement the methods in the Service interface
Control layer
Controller: it is responsible for request forwarding and accepting the parameters passed from the page. According to different parameters, it calls different Service layer methods for operation, and passes the returned results to the page after the operation is completed.
Common notes
Pojo layer
@TableName("user") //Implement the mapping between object and database table name @Data //Automatically generate get/set/toString methods @Accessors(chain = true) //Open chain loading @TableId(type = IdType.AUTO) //Primary key auto increment @TableField(exist = false) //The property does not exist
Controller layer
@RestController //The annotated method represents a controller and returns json @CrossOrigin //Solve cross domain problems @Autowired //Complete the dependencies between objects spring Di; The bottom layer helps you maintain the relationship between two objects: new @RequestMapping("route") //Request path @getMapping("") //query @PostMapping("") //newly added @PutMapping("") //modify @DeleteMapping("") //delete @ResponseBody //Convert object to json string @RequestBody //Convert json string to user object
Service layer
@Service @Autowired @Transactional //The transaction is started, and either interface based or class based proxies are created
demo1: judge whether the server call is successful
package com.jt.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor public class SysResult { private Integer status; //Status code information private String msg; //Prompt information private Object data; //Encapsulate business data public static SysResult fail(){ return new SysResult(201,"Server call failed",null); } public static SysResult success(){ return new SysResult(200,"Successful business execution",null); } /** * 1.Method to be called by others * 2.When the method is called, the caller is responsible for passing the parameters * @param data * @return * */ public static SysResult success(Object data){ return new SysResult(200,"Successful business execution",data); } public static SysResult success(String msg, Object data){ return new SysResult(200,msg,data); } }
demo2: judge whether the data is valid according to the user name
Judge whether the data is valid according to the user name and password * Steps: * 1.Encrypt the plaintext. md5 encryption/md5Hash/sha1 * 2.Query the database according to the encrypted data * 3.Judge whether the result is valid * With value: returns a specific string token=123 * null: u/p Uncertain return null @Override @Transactional public String login(User user) { //1. Obtain the original password String password = user.getPassword(); //2. Encrypt the password String md5Str = DigestUtils.md5DigestAsHex(password.getBytes()); //3. Pass the ciphertext to the object user.setPassword(md5Str);//username/password //Act as a where condition based on non null properties in the object QueryWrapper<User> queryWrapper = new QueryWrapper<>(user); //4. Query database according to conditions User userDB = userMapper.selectOne(queryWrapper); //5. Define the token data qualification. Tokens cannot be repeated String uuid = UUID.randomUUID().toString() .replace("_", ""); // UUID: random string 3.4 * 10 ^ 38 possibilities hash (timestamp + random number) return userDB ==null?null:uuid; }
demo3: using MP to realize paging query
/** * Using MP to realize paging query * API selectPage(arg1,arg2) * arg1: MP The paging object in is fixed * arg2: MP Conditional constructor in paging * @param pageResult * @return * Dynamic sql: select * from user where username like "admin" * Condition: if the user passes query, the where condition is used; otherwise, the where condition is not spliced * */ @Override public PageResult getUserList(PageResult pageResult) { //1. Define the paging object of mp IPage iPage = new Page(pageResult.getPageNum(),pageResult.getPageSize()); //2. Build query condition constructor QueryWrapper queryWrapper = new QueryWrapper(); //Judge whether the user data is valid. The valid value is true. The invalid value is false boolean flag = StringUtils.hasLength(pageResult.getQuery()); queryWrapper.like(flag, "username", pageResult.getQuery()); //After MP paging query, all paging data is encapsulated into iPage objects iPage = userMapper.selectPage(iPage, queryWrapper); long total = iPage.getTotal(); //Gets the total number of records from the paging object List<User> rows = iPage.getRecords(); //Get the paged result from the paged object return pageResult.setTotal(total).setRows(rows); }
demo4: adding new users
@Override @Transactional public void addUser(User user) { String password = user.getPassword(); //Password encryption operation String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes()); //Assign an operation to a property user.setStatus(true).setPassword(md5Pass); //Implement receipt operation userMapper.insert(user); }
demo5: three level menu information acquisition
@Service public class ItemCatServiceImpl implements ItemCatService{ @Autowired private ItemCatMapper itemCatMapper; /** * 1.Prepare the Map collection to realize data encapsulation * Map<key,value> = Map<parentId,List<ItemCat>> * 2.Package business description * map Middle key~~parentId * Does not exist: the key can be stored * At the same time, encapsulate a List collection and encapsulate yourself as the first element * Existence: get all child sets according to the key and append yourself to form the second element */ public Map<Integer,List<ItemCat>> itemCatMap(){ //1. Define Map set Map<Integer,List<ItemCat>> map = new HashMap<>(); //2. Query all database information 1-2-3 List<ItemCat> list = itemCatMapper.selectList(null); for(ItemCat itemCat :list){ int parentId = itemCat.getParentId();//Get parent ID if(map.containsKey(parentId)){ //Judge whether there is a parentId in the collection //A key gets the list set and appends itself to the set List<ItemCat> exeList = map.get(parentId);//Reference object exeList.add(itemCat); }else{ //Without a key, encapsulate yourself as the first list element List<ItemCat> firstList = new ArrayList<>(); firstList.add(itemCat); map.put(parentId,firstList); } } return map; } @Override public List<ItemCat> findItemCatList(Integer level) { long startTime = System.currentTimeMillis(); Map<Integer,List<ItemCat>> map = itemCatMap(); //1. If level=1, it means to obtain the primary commodity classification information parent_id=0 if(level == 1){ return map.get(0); } if(level == 2){ //Get primary and secondary menu information return getTwoList(map); } //3. Obtain three-level menu information //3.1 get the secondary commodity classification information BUG: how to deal with some data that may not have children List<ItemCat> oneList = getTwoList(map); for (ItemCat oneItemCat : oneList){ //From the primary collection, get the secondary menu list List<ItemCat> twoList = oneItemCat.getChildren(); for(ItemCat twoItemCat : twoList){ //Query criteria for Level 3 commodity classification: parentid = level 2 ID List<ItemCat> threeList = map.get(twoItemCat.getId()); twoItemCat.setChildren(threeList); } } long endTime = System.currentTimeMillis(); System.out.println("time consuming:"+(endTime - startTime)+"millisecond"); return oneList; } public List<ItemCat> getTwoList(Map<Integer,List<ItemCat>> map){ List<ItemCat> oneList = map.get(0); for (ItemCat oneItemCat : oneList){//Query Level 2 parentid = level 1 Id List<ItemCat> twoList = map.get(oneItemCat.getId()); oneItemCat.setChildren(twoList); } //The second level is nested in the first level set, and all that is always returned is level 1 return oneList; } /** * 3 Level 1 commodity classification nested level 1 Classification (children (Level 2 commodity classification)) * 2 Primary classification (children) * First level query criteria parent_id=0 * Secondary query criteria parent_id = ID of level 1 * Level 3 query criteria parent_id = secondary ID * @param level * @return */ /* @Override public List<ItemCat> findItemCatList(Integer level) { long startTime = System.currentTimeMillis(); //1.Query primary commodity classification information QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("parent_id",0 ); List<ItemCat> oneList = itemCatMapper.selectList(queryWrapper); //2.Query secondary commodity classification information for (ItemCat oneItemCat : oneList){ queryWrapper.clear(); queryWrapper.eq("parent_id",oneItemCat.getId()); List<ItemCat> twoList = itemCatMapper.selectList(queryWrapper); //3.Query Level 3 commodity classification information for (ItemCat twoItemCat : twoList){ queryWrapper.clear(); queryWrapper.eq("parent_id",twoItemCat.getId()); List<ItemCat> threeList = itemCatMapper.selectList(queryWrapper); twoItemCat.setChildren(threeList); } oneItemCat.setChildren(twoList); } long endTime = System.currentTimeMillis(); System.out.println("The execution time of the service is: "+ (Endtime starttime) +" milliseconds "); return oneList; }*/ }
demo6: Global exception handling
//For global exception handling, the method of surrounding notification is still adopted internally //JSON string returned after exception handling //This global exception handling mechanism captures exceptions of the Controller layer (exceptions thrown upward by other layers) @RestControllerAdvice public class MyException { /** * Business: if the back-end reports an error, the front-end user should be prompted in time to return a unified object * SysResult Object status=201/msg="xxx failed" * Notes: * @ExceptionHandler(RuntimeException.class) * When an exception is encountered, the global exception handling mechanism is effective!! */ @ExceptionHandler(RuntimeException.class) public Object exception(Exception e){ //1. Abnormal information should be printed e.printStackTrace(); //2. Return specific response data return SysResult.fail(); } }
demo7: delete commodity classification
/** * Policy: if it is a parent, the child should be deleted * @param itemCat */ @Override @Transactional public void deleteItemCat(ItemCat itemCat) { //1. Judge whether it is a three-level menu if(itemCat.getLevel() == 3){ //If it is level 3 Delete directly itemCatMapper.deleteById(itemCat.getId()); return; //Termination of the procedure } //2. Check whether the menu is level 2 if(itemCat.getLevel() == 2){ //Three levels of parent should be deleted first_ Id = level 2 ID QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("parent_id",itemCat.getId()); itemCatMapper.delete(queryWrapper); //Then delete the level 2 menu itemCatMapper.deleteById(itemCat.getId()); return; } //To delete level 1 commodity classification information, first delete Level 3 Delete Level 2 again //1. First, obtain the level 2 information parent of commodity classification_ Id = level 1 ID QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("parent_id",itemCat.getId()); List<ItemCat> twoList = itemCatMapper.selectList(queryWrapper); for (ItemCat twoItemCat : twoList){ queryWrapper.clear(); queryWrapper.eq("parent_id",twoItemCat.getId()); itemCatMapper.delete(queryWrapper);//Delete Level 3 menu itemCatMapper.deleteById(twoItemCat.getId());//Delete Level 2 } itemCatMapper.deleteById(itemCat.getId()); //Delete level 1 }