SSM technology integration of SpringBoot

Posted by fgm on Fri, 21 Jan 2022 20:11:43 +0100

1, SpringBoot build

① . building modules

Spring Web: integrate ssm environment and build server;

MyBatis Framework: integrate MyBatis;

MySQL Driver: database;

② . yml file

server:
  port: 8080

2, MBG reverse engineering

1. Connect to database

2. Code generation

① Import reverse engineering dependency

<!--Reverse engineering dependency-->
<dependency>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-core</artifactId>
	<version>1.3.7</version>
</dependency>

<!--plug-in unit-->
<plugin>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.3.7</version>
	<configuration>
	    <configurationFile>
		<!--Here is the configuration generatorConfig.xml The default path is not written in resources Find under directory generatorConfig.xml file-->
	    </configurationFile>
	    <verbose>true</verbose>
	    <overwrite>true</overwrite>
	</configuration>
</plugin>

② , import configuration file

In the resource package:

Generator.properties:userSSL means unencrypted; serverTimezone: time zone; useUnicode: prevent garbled code; allowPublicKeyRetrieval: allow encrypted access

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/aaa?userSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123456
jdbc.driverLocation=E:\\MavenCangku\\localCangKu\\mysql\\mysql-connector-java\\8.0.25\\mysql-connector-java-8.0.25.jar

model.package=com.lv.code.pojo
mapper.package=com.lv.code.dao
xml.mapper.package=mapper

generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="generator.properties"/>
    <!--Specify database jdbc drive jar Package location-->
    <classPathEntry location="${jdbc.driverLocation}"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <!--generate mapper.xml Overwrite original file when-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
        <plugin type="org.mybatis.generator.plugins.MyBatisPlugin">
            <property name="hasLombok" value="true"/>
        </plugin>
        <!--You can customize the generation model Code comments for-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/> <!-- Uncomment -->
            <property name="suppressDate" value="true"/> <!-- Generate comment generation timestamp -->
        </commentGenerator>

        <!--Configure database connection-->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
            <!--solve mysql Driver upgrade to 8.0 The specified database code will not be generated after-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!-- Not required, type processor, in database type and java Conversion control between types-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--appoint pojo Generation location-->
        <javaModelGenerator targetPackage="${model.package}" targetProject="src\main\java"/>

        <!--Specify build mapper.xml Path of-->
        <sqlMapGenerator targetPackage="${xml.mapper.package}" targetProject="src\main\resources"/>

        <!--Specify build mapper Path of the interface-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="${mapper.package}"
                             targetProject="src\main\java"/>

        <table tableName="student" domainObjectName="Student">
            <!--<columnOverride column="create_time" javaType="java.sql.Timestamp" jdbcType="timestamp"/>-->
            <!--<columnOverride column="modify_time" javaType="java.sql.Timestamp" jdbcType="timestamp"/>-->
            <property name="enableCountByExample" value="false"/>
            <property name="enableDeleteByExample" value="false"/>
            <property name="enableDeleteByPrimaryKey" value="false"/>
            <property name="enableInsert" value="false"/>
            <property name="enableSelectByPrimaryKey" value="false"/>
            <property name="enableUpdateByExample" value="false"/>
            <property name="enableUpdateByPrimaryKey" value="false"/>
            <property name="selectByExampleQueryId" value="true"/>
            <property name="selectByPrimaryKeyQueryId" value="false"/>
            <!--Auto generate primary key,Can replace useGeneratedKeys-->
            <generatedKey column="stu_id" sqlStatement="Mysql" type="post" identity="true"/>
        </table>

    </context>
</generatorConfiguration>

③ , generate annotations on table objects and annotations on documents

Create a new software package in the Java package. The package name is the same as this. Org mybatis. generator. plugins

package org.mybatis.generator.plugins;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hgh
 */
@Slf4j
public class MyBatisPlugin extends PluginAdapter {

    @Override
    public boolean validate(List<String> list) {
        return true;
    }

//    Generate comments above class
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        boolean hasLombok = Boolean.parseBoolean(getProperties().getProperty("hasLombok", "false"));
        log.warn("hasLombok:\t" + hasLombok);
        if (hasLombok) {
            topLevelClass.addImportedType("lombok.Data");
            topLevelClass.addImportedType("lombok.NoArgsConstructor");
            topLevelClass.addImportedType("lombok.AllArgsConstructor");
            topLevelClass.addImportedType("lombok.experimental.Accessors");
            topLevelClass.addAnnotation("@Data");
            topLevelClass.addAnnotation("@NoArgsConstructor");
            topLevelClass.addAnnotation("@AllArgsConstructor");
            topLevelClass.addAnnotation("@Accessors(chain = true)");
        }
        topLevelClass.addJavaDocLine("/**");
        String remarks = introspectedTable.getRemarks();
        log.error("@table\t" + remarks);
        topLevelClass.addJavaDocLine(" * "+remarks + "\t" + introspectedTable.getFullyQualifiedTable());
        topLevelClass.addJavaDocLine(" * @author lv");
        topLevelClass.addJavaDocLine(" * @date " + LocalDateTime.now());
        topLevelClass.addJavaDocLine(" */");
        return true;
    }

//    Generate comments on each field
    @Override
    public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        field.addJavaDocLine("/**");
        String remarks = introspectedColumn.getRemarks();
        log.error("@column\t" + remarks);
        field.addJavaDocLine(" * " + remarks);
        field.addJavaDocLine(" */");
        return true;
    }

//    Generate interface annotations
    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper"));
        interfaze.addAnnotation("@Mapper");
        interfaze.addImportedType(new FullyQualifiedJavaType("org.springframework.stereotype.Repository"));
        interfaze.addAnnotation("@Repository");
        interfaze.addJavaDocLine("/**");
        interfaze.addJavaDocLine(" * @author hgh");
        interfaze.addJavaDocLine(" * @date " + LocalDateTime.now());
        interfaze.addJavaDocLine(" */");
        return true;
    }

//    Does the model need to generate a set method
    @Override
    public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        boolean hasLombok = Boolean.parseBoolean(getProperties().getProperty("hasLombok", "false"));
        return !hasLombok;
    }

//    Does the model need to generate get methods
    @Override
    public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        boolean hasLombok = Boolean.parseBoolean(getProperties().getProperty("hasLombok", "false"));
        return !hasLombok;
    }

}

Throw the compiled file of this class into POM In the jar package of the corresponding version in the mybatis generator core file referred to in the XML file:

First, execute the following file to obtain the compiled file:

Drop this file into the local repository: e: \ maven cangku \ localcangku \ ORG \ mybatis \ generator \ mybatis generator core \ 1.3.7

Put in plugins file:

④. Execute generated code

Double click:

Successfully generated:

3. Configure data source and mybatis

application.yml file:

server:
  port: 8080
#  Configure data sources
spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/aaa?userSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true
#Configure mybatis, enable alias, and enable hump nomenclature
mybatis:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.lv.code.pojo
  configuration:
    map-underscore-to-camel-case: true
#  Log printing
logging:
 level:
  com.lv.code.dao: debug

4. Query table data

StudentMapper.java:

package com.lv.code.dao;

import com.lv.code.pojo.Student;
import com.lv.code.pojo.StudentExample;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

/**
 * @author lv
 * @date 2022-01-20T18:59:38.176
 */
@Mapper
@Repository
public interface StudentMapper {
    List<Student> select();

}

StudentMapper.xml:

 <select id="select" resultType="com.lv.code.pojo.Student">
    select * from student
  </select>

Test: springboot03 application tests java

package com.lv.code;

import com.lv.code.dao.StudentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;

@SpringBootTest
class SpringBoot03ApplicationTests {
    @Autowired
    DataSource dataSource;

    @Autowired
    StudentMapper mapper;

    @Test
    void contextLoads() throws Exception{
        System.out.println(dataSource);
//        Get connected
        System.out.println(dataSource.getConnection());
        System.out.println(mapper.select());
    }

}

3, SSM development

StudentService: 
package com.lv.code.service;

import com.lv.code.pojo.Student;
import com.lv.code.util.PageBean;

import java.util.List;

public interface StudentService {

    List<Student> selectPager(PageBean pageBean);

    Student selectOne(Student student);

    int add(Student student);

    int del(Student student);

    int upd(Student student);

}
StudentServiceImpl: 
package com.lv.code.service;

import com.lv.code.dao.StudentMapper;
import com.lv.code.pojo.Student;
import com.lv.code.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    private StudentMapper mapper;
    @Autowired
    public StudentServiceImpl(StudentMapper mapper){
        this.mapper=mapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Student> selectPager(PageBean pageBean) {
        return mapper.select();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Student selectOne(Student student) {
        return mapper.selectOne(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(Student student) {
        return mapper.add(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int del(Student student) {
        return mapper.del(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int upd(Student student) {
        return mapper.upd(student);
    }
}
StudentMapper.java:
package com.lv.code.dao;

import com.lv.code.pojo.Student;

import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * @author lv
 * @date 2022-01-20T18:59:38.176
 */

@Repository
public interface StudentMapper {
    List<Student> select();

    Student selectOne(Student student);

    int add(Student student);

    int del(Student student);

    int upd(Student student);

}
StudentController.java:
package com.lv.code.controller;


import com.lv.code.pojo.Student;
import com.lv.code.service.StudentService;
import com.lv.code.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/stu")
public class StudentController {

//    restful architecture
//Request: get data; Add post; Delete delete; put, patch modification

    StudentService service;
    @Autowired
    public StudentController(StudentService service){
        this.service=service;
    }

    @GetMapping
    public Object select(HttpServletRequest request){
        PageBean pageBean=new PageBean();
        pageBean.setRequest(request);
        return service.selectPager(pageBean);
    }

    @GetMapping("/{stuId}")
    public Object selectOne(@PathVariable Long stuId){
        return service.selectOne(new Student().setStuId(stuId));
    }

    @DeleteMapping("/{stuId}")
    public Object del(@PathVariable Long stuId){
        return service.del(new Student().setStuId(stuId));
    }

    @PostMapping
    public Object add(Student student){
        return service.add(student);
    }

    @PutMapping
    public Object upd(Student student){
        return service.upd(student);
    }


}

StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lv.code.dao.StudentMapper">
  <resultMap id="BaseResultMap" type="com.lv.code.pojo.Student">
    <id column="stu_id" jdbcType="BIGINT" property="stuId" />
    <result column="stu_name" jdbcType="VARCHAR" property="stuName" />
    <result column="stu_phone" jdbcType="VARCHAR" property="stuPhone" />
    <result column="stu_class" jdbcType="BIGINT" property="stuClass" />
    <result column="stu_address" jdbcType="VARCHAR" property="stuAddress" />
  </resultMap>
  <select id="select" resultType="com.lv.code.pojo.Student">
     select * from student
  </select>

  <select id="selectOne" resultType="com.lv.code.pojo.Student">
        select * from student where stu_id=#{stuId}
  </select>

  <insert id="add">
    insert into student(stu_name, stu_phone, stu_class,stu_address)
    values (#{stuName},#{stuPhone},#{stuClass},#{stuAddress})
  </insert>

  <delete id="del">
    delete from student where stu_id=#{stuId}
  </delete>

  <update id="upd">
    update student set stu_name=#{stuName} where stu_id=#{stuId}
  </update>


</mapper>

SpringBoot03Application: start the transaction manager

@EnableTransactionManagement

4, Integrated PageHelper

Import dependency:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper-spring-boot-starter</artifactId>
  <version>1.2.10</version>
</dependency>

Start class springboot03application Java: open automatic proxy

@EnableAspectJAutoProxy

PageBean.java:

package com.lv.code.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Silver ho
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean {

    private int total;
    private int page = 1;
    private int rows = 5;
    private boolean pagination = true;
    private String url;
    private Map<String, String[]> ms;

    public void setMs(Map<String, String[]> ms) {
        this.ms = ms;
    }

    public int calcStartIndex() {
        return (page - 1) * rows;
    }

    public int calcMaxPage() {
        return total % rows == 0 ? total / rows : total / rows + 1;
    }

    public int nextPage() {
        return Math.min(page + 1, calcMaxPage());
    }

    public int prevPage() {
        return Math.max(page - 1, 1);
    }

    public void setRequest(HttpServletRequest req) {
        setUrl(req.getRequestURL().toString());
        setMs(req.getParameterMap());
        String page = req.getParameter("page");
        if (page == null) {
            setPage(1);
        } else {
            setPage(Integer.parseInt(page));
        }
        String rows = req.getParameter("rows");
        if (rows == null) {
            setRows(5);
        } else {
            setRows(Integer.parseInt(rows));
        }
        String pagination = req.getParameter("pagination");
        if ("false".equals(pagination)) {
            setPagination(false);
        }
    }

}

Paging aspect: pageaspect java

package com.lv.code.aspect;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yk.code.util.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author yk
 */
@Component
@Aspect
@Slf4j
public class PageAspect {

    @Around(value = "execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint point) throws Throwable {
        PageBean pageBean = null;
        for (Object e : point.getArgs()) {
            if (e instanceof PageBean) {
                pageBean = (PageBean) e;
                break;
            }
        }
        if (pageBean != null && pageBean.isPagination()) {
            PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
        }
        Object obj = point.proceed(point.getArgs());
        if (obj != null) {
            if (obj instanceof Page) {
                Page page = (Page) obj;
                PageInfo pageInfo = new PageInfo(page);
                pageBean.setTotal(new Long(pageInfo.getTotal()).intValue());
                return pageInfo.getList();
            }
        }
        return obj;
    }

}

Change the method to use paging:

StudentServiceImpl: 
  @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Student> selectPager(PageBean pageBean) {
        return mapper.select();
    }
StudentService:
List<Student> selectPager(PageBean pageBean);
StudentController:
 @GetMapping
    public Object select(HttpServletRequest request){
        PageBean pageBean=new PageBean();
        pageBean.setRequest(request);
        return service.selectPager(pageBean);
    }

5, Integrated general mapper

1. Import dependency

<dependency>
 <groupId>tk.mybatis</groupId>
 <artifactId>mapper-spring-boot-starter</artifactId>
 <version>2.0.2</version>
</dependency>

2. Start in the startup class: directly implement the package name, and its mapper file does not need to write @ mapper annotation for each

//Automatically scan mapper files
@MapperScan("com.lv.code.dao")

It can automatically generate methods, remove the sql statements in xml, and there is no need to write methods in mapper. Only mapper can be inherited

However, the following methods can be called:

System.out.println(mapper.selectAll());
//Query single
 System.out.println(mapper.selectByPrimaryKey(new Student().setStuId(1L)));
//        Benchmark query
        System.out.println(mapper.select(new Student().setStuName("Marco Polo")));
//        Fuzzy query
        Example example=new Example(Student.class);
        Example.Criteria c=example.createCriteria();
        c.andLike("stuName","'%horse%'");
        mapper.selectByExample(example);

result:

 

Basic interface:

setDistinct(boolean distinct) whether to filter the uniqueness of query results. true indicates filtering, and false (default)
(yes) indicates no filtering.
Criteria
void setOrderByClause(String orderByClause) the query results are sorted in ascending and descending order according to a or some fields
Preface.
For example, the parameter "id asc" is in ascending order by id, and "id asc, age desc" is in ascending order by id, where IDs are equal
In the case of, in descending order of age.
Example selectProperties(String... properties) when querying with example, this method can
Set which fields you want to query
Example.OrderBy orderBy(String property) sorting has the same function as setOrderByClause, except that
Different usage
For example, orderby ("id") ASC () means in ascending order of id,
orderBy("id").asc().orderBy("age").desc() means ascending by ID and descending by age
Example.Criteria or() creates an or style, empty criteria
Void or (example. Criteria criteria criteria) directly adds an existing criteria in the form of or
Example.Criteria and() is the same as above, but it is the and method
void and(Example.Criteria criteria) as above, and

criteria. Andisnull (segment name);
Add a condition where the field xx is null
criteria. Andisnotnull (field name);
Add a condition that field xx is not null
criteria. Andequalto (field name, value);
Add xx field equal to value condition
criteria. Andnotequalto (field name, value);
Add condition that xx field is not equal to value
criteria. Andgreaterthan (field name, value);
Add the condition that xx field is greater than value
criteria. Andgreaterthanorequalto (field name, value);
Add the condition that xx field is greater than or equal to value
criteria. Andlessthan (field name, value);
Add the condition that xx field is less than value
criteria. Andlessthanorequalto (field name, value);
Add the condition that xx field is less than or equal to value
criteria. Andin (field name, list);
Add xx field value in List condition
criteria. Andnotin (field name, list);
Add xx field value is not in the List condition
criteria. Andlike (field name, "%" + value + "%");
Add a fuzzy query condition with xx field value as value
criteria. Andnotlike (field name, "%" + value + "%");
Condition
Add a fuzzy query condition in which the value of xx field is not value
criteria. Andbetween (field name, value1,value2);
Add the condition that the xx field value is between value1 and value2
criteria. Andnotbetween (field name, value1,value2);
Add the condition that the value of xx field is not between value1 and value2
Example. The criteria orcondition (string condition, object value) condition parameter is a
The sql string can be spliced into the sql statement. Value is a value and will be spliced to the end of the condition method
The result is or condition + value.
Example. The function of criteria orcondition (string condition) is the same as above, but it is more direct. It is a string
Yes, but the string parameters can be written as "id =" + getId(), "(id =" + getId() + ")"
The final result of the method is or condition.
Example.Criteria andCondition(String condition) is the same as above
Example. Criteria and condition (string condition, object value) are the same as above

3. Table annotation

① . dependency:

<dependency>
 <groupId>javax.persistence</groupId>
 <artifactId>persistence-api</artifactId>
 <version>1.0</version>
 <scope>compile</scope>
</dependency>

② . directly specify the table name and attribute name of the table in the entity class:

@Table(name = "student")
//Specify the database property name in the corresponding property
@Column(name = "stu_id")

@Table(name="tb_brand") specifies which table in the database to map
@id indicates that the member variable is the primary key id
@GeneratedValue(strategy = GenerationType.IDENTITY) identifies the policy of the primary key and is self incremented
@Column(name = "name") identifies the mapping between the member variable and the name field in the database
@Transient is not a table field

End of current period~~~~~~~~

Topics: linq p2p GNU