Cat学习Java一:SSM完整整合自用模板

SSM完整整合模版

一、开发环境的准备:

1.1、开发环境Pom的环境准备:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>SSM_Jquery_Ajax</name>
  <groupId>org.qf</groupId>
  <artifactId>SSM_Jquery_Ajax</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!--单元测试的包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!-- servlet3.1包 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- jsp-api包 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- jstl包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- 数据库驱动包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>

    <!-- c3p0连接池包-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>mchange-commons-java</artifactId>
      <version>0.2.11</version>
    </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <!--spring包-->
    <!--spring的核心包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--spring的ioc包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--spring的容器包,增强ioc和aop,还支持与其他框架整合-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--spring的容器辅助包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--spring的aop的包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--spring的表达式语言的包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!--spring对象映射的包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--spring的事务的包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!--spring的web项目支持的包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--springmvc所需要的包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!--spring的jdbc的包
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>-->

    <!-- 为了方便进行单元测试,添加spring-test包
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.1.3.RELEASE</version>
    </dependency>-->

    <!--json转换器-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.10</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.10</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.10</version>
    </dependency>

    <!--fastjson包-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.5</version>
    </dependency>

    <!-- 上传所需要的包
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.4</version>
    </dependency>-->

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>-->

    <!--thymeleaf依赖包-->
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf</artifactId>
      <version>3.0.11.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>3.0.11.RELEASE</version>
    </dependency>

    <!-- 添加mybatis的核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <!-- 添加mybatis与Spring整合的核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mybatis的缓存-->
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.1.0</version>
    </dependency>

    <!--MyBatis Generator自动生成实体类和接口及映射文件的Jar包-->
    <!--为了应对属性和字段名的不对应-->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.5</version>
    </dependency>

    <!-- 日志包 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>
    <!-- slf4j日志框架和log4j 转换包 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.7</version>
    </dependency>

    <!--日志包-->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging-api</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
    </dependency>

    <!--分页插件-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>


      <!-- 编译插件,指定编译用的jdk版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version><!-- 必须指定版本 -->
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>

      <!--配置MyBatis Generator自动生成插件-->
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.5</version>
        <configuration>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>
    </plugins>
    <!--识别配置文件-->
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <!-- 是否替换资源中的属性-->
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

</project>

1.2、开发环境web.xml的环境准备:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <welcome-file-list>
    	<!--如果是模本文件,一定要先进控制器,再跳静态页面,要先激活模板解析器-->
        <!--<welcome-file>/WEB-INF/static/page/TestAjax.html</welcome-file>-->
    </welcome-file-list>
    
    <!--监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!--指定主配置文件的位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--springmvc的配置文件-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--启动加载的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext_controller.xml</param-value>
        </init-param>
        <!--启动的顺序-->
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!--<url-pattern>/</url-pattern>    除去jsp静态不会拦截,其他的都会拦截-->
        <!--可以通过配置文件来放行静态资源-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置字符编码过滤-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern><!--对所有请求响应的资源进行拦截-->
    </filter-mapping>
</web-app>
        
        

1.3、准备数据库文件和日志配置文件:

c3p0.driverClass=com.mysql.cj.jdbc.Driver
c3p0.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
c3p0.username=username
c3p0.password=password
//版本数据库为8.0+
#设置Logger输出级别和输出目的地
log4j.rootLogger=DEBUG, Console ,logfile
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n 
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG 

### 把日志信息输出到文件###
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=qf.log
log4j.appender.logfile.DatePattern = '.'yyyy-MM-dd
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %F %p %m%n

二、配置文件的编写:

ssm整合有多种方法,可以将所有的spring的配置文件写在一个文件里面,也可以将文件各自分开,然后用一个总的容器来管理。值得注意的是,springIOC容器是一个容器,springMVC是一个容器。一个是父容器,一个是子容器。

这里采用的是分开配置容器,使用一个总的容器来管理。这样看起来更清晰。

applicationContext_service.xml:这个配置文件包含service层和dao层,对应着spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--1、配置dao层-->
    <!--1.1,加载数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!--1.2,配置数据库DataSource-->
    <bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${c3p0.driverClass}"></property>
        <property name="jdbcUrl" value="${c3p0.url}"></property>
        <property name="user" value="${c3p0.username}"></property>
        <property name="password" value="${c3p0.password}"></property>
        <!--初始化连接数-->
        <property name="initialPoolSize" value="10"></property>
        <!--最小连接数-->
        <property name="minPoolSize" value="10"></property>
        <!--最大连接数-->
        <property name="maxPoolSize" value="30"></property>
        <!--重试等待时间-->
        <property name="checkoutTimeout" value="6000"></property>
    </bean>
    <!--1.3,配置数据库的sqlSessionFactroyBean-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="DataSource"></property>
        <!--mapper文件的位置-->
        <property name="mapperLocations" value="classpath:com/qf/dao/mapper/*.xml"></property>
        <property name="typeAliasesPackage" value="com.XX.pojo"></property>
    </bean>
    <!--1.4,配置mapper接口dao扫描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
        <!--mapper的namespace对应的接口的位置-->
        <property name="basePackage" value="com.XX.dao"></property>
    </bean>

    <!--1.5,配置事物-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="DataSource"></property>
    </bean>
    <!--开启注解事物-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!--2、配置service层-->
    <!--2.1,将service纳入到springioc容器中来-->
    <context:component-scan base-package="com.XX.service.impl,com.XX.dao">
        <context:exclude-filter type="annotation" 		expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

applicationContext_Controller.xml:这里只包含Controller层,对应springmvc

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--1,扫描controller所在的包-->
    <context:component-scan base-package="com.XX.controller">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
    <!--2,开启注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--3,放行静态资源,:*:表示文件,:**:表示文件-->
    <mvc:resources mapping="/WEB-INF/static/**" location="/WEB-INF/static/"></mvc:resources>

    <!--4,配置视图解析器-->
    <!--4.1,配置Thymeleaf视图解析器-->
    <bean id="springResourceTemplateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/static/page/"></property>
        <!--后缀-->
        <!--<property name="suffix" value=".html"></property>-->
        <!--文件类型,值固定-->
        <property name="templateMode" value="HTML"></property>
        <!--字符编码-->
        <property name="characterEncoding" value="UTF-8"></property>
        <!--缓存-->
        <property name="cacheable" value="false"></property>
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="springResourceTemplateResolver"></property>
    </bean>
    <bean id="thymeleafViewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"></property>
        <property name="characterEncoding" value="UTF-8"></property>
    </bean>

    <!--4.2配置其他类型的视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/static/page/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--5,配置json数据类型解析器-->

    <!--json乱码问题的配置-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"></constructor-arg>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"></property>
                    </bean>
                </property>
            </bean>
            <!--fastjson的配置-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
                <property name="defaultCharset" value="UTF-8"></property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--视图解析器-->
    <bean id="internalResourceViewResolver2" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <!--后缀-->
    </bean>


</beans>

applicationContext.xml:管理service和controller容器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--导入另外的两个的配置文件-->
    <import resource="classpath:applicationContext_service.xml"></import>
    <import resource="classpath:applicationContext_controller.xml"></import>
</beans>

值得注意的是:导入两个配置文件是有先后顺序的,一定是先导入service,然后再导入controller。有时会因为顺序不同导致报错。

三、开始编写具体的代码:

数据库的字段名和类的属性最好保持一致,如果不一致,通过别名和resultMap来配置。或者可以通过逆向工程文件来生成。

pojo:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
    private Integer stuNo;
    private String stuName;
    private String stuSex;
    private Integer stuAge;
}

dao:

public interface StudentMapper {
    Student selectStudentById(@Param("stuNo") Integer stuNo);
}

mapper:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.XX.dao.StudentMapper">
    <resultMap id="student_map" type="Student">
        <id property="stuNo" jdbcType="INTEGER" column="stuNo"></id>
        <result property="stuName" jdbcType="VARCHAR" column="stuName"></result>
        <result property="stuSex" jdbcType="VARCHAR" column="stuSex"></result>
        <result property="stuAge" jdbcType="INTEGER" column="stuAge"></result>
    </resultMap>

    <sql id="student_column">
        stuNo as stuNo,stuName as stuName,stuSex as stuSex,stuAge as stuAge
    </sql>

    <select id="selectStudentById" parameterType="int" resultMap="student_map">
        select
        <include refid="student_column"></include>
        from t_student
        <where>
            <if test="#{stuNo} != null || #{stuNo} != ''">
                stuNo=#{stuNo}
            </if>
        </where>

        <!--select <include refid="student_column"></include> from t_student where stuNo=#{stuNo}-->
    </select>

</mapper>

service:

接口:

public interface IStudentService {
    Student selectStudentById(int stuNo);
}

实现类:

@Service
@Transactional
public class StudentServiceImpl implements IStudentService {

    @Autowired(required = true)
    @Qualifier(value = "studentMapper")
    public StudentMapper studentMapper;
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Student selectStudentById(int stuNo) {
        Student student = studentMapper.selectStudentById(stuNo);
        return student;
    }
}

Controller:

@Controller
@RequestMapping("/s")
public class StudentController {

    @Autowired(required = true)
    @Qualifier(value = "studentServiceImpl")
    private IStudentService studentService;

    @GetMapping("/m1")
    @ResponseBody
    public Student methodAjaxTest01(int stuNo){
        Student student = studentService.selectStudentById(stuNo);
        return student;
    }
}

四:逆向工程的配置文件:

第一种:通过maven->plugins->mybatis-generator->mybatis-generator:generate->单击右键->Run maven build(前提是mybatis-generator包导入,以及maven配置了generator的插件。)

<?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 >
    <!-- 链接数据库的jar包的完整路径,一定要注意跟自己的仓库路径一致 ,注意修改  -->
    <classPathEntry location="D:\Personal application\Java\maven\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar" ></classPathEntry>
    <context id="context1" >
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />

        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/1913myschool?useUnicode=true&amp;characterEncoding=UTF-8&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC&amp;useSSL=false"
                        userId="root"
                        password="123a" />
        <!-- 生成POJO类的位置,targetPackage生成的实体类的包名,targetProject是实体类包名生成的位置 -->
        <javaModelGenerator targetPackage="com.qf.pojo" targetProject="src/main/java" />
        <!-- mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.qf.mapper" targetProject="src/main/java" />
        <!-- mapper接口生成的位置 -->
        <javaClientGenerator targetPackage="com.qf.dao" targetProject="src/main/java" type="XMLMAPPER" />
        <!-- tableName指定数据库表  domainObjectName实体的名称
      <table  tableName="userinfo" domainObjectName="Userinfo"
			自动生成增删除改查的方法和映射sql例子-->
        <!--
        统计总数的sql案例
        enableCountByExample="false"
        修改的案例
        enableUpdateByExample="false"
        查询的案例
        enableSelectByExample="false"
        删除的案例
        enableDeleteByExample="false"
        ></table>
        -->
    <table  tableName="stu" domainObjectName="Student"
            enableCountByExample="false"
            enableUpdateByExample="false"
            enableSelectByExample="false"
            enableDeleteByExample="false"
    ></table>
    <table  tableName="course" domainObjectName="Course"
            enableCountByExample="false"
            enableUpdateByExample="false"
            enableSelectByExample="false"
            enableDeleteByExample="false"
    ></table>
        <table  tableName="score" domainObjectName="Score"
                enableCountByExample="false"
                enableUpdateByExample="false"
                enableSelectByExample="false"
                enableDeleteByExample="false"
        ></table>
</context>
</generatorConfiguration>

第二种:直接建一个测试文件执行:
同上,也是generator.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>
	<context id="DB2Tables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- suppressAllComments属性值: true:自动生成实体类、SQL映射文件时没有注释 true:自动生成实体类、SQL映射文件,并附有注释 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!-- 数据库连接信息 -->
		<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/testmybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC&amp;useSSL=false" userId="root"
			password="123a">
		</jdbcConnection>
		<!-- forceBigDecimals属性值: true:把数据表中的DECIMAL和NUMERIC类型, 解析为JAVA代码中的java.math.BigDecimal类型 
			false(默认):把数据表中的DECIMAL和NUMERIC类型, 解析为解析为JAVA代码中的Integer类型 -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>
		<!-- targetProject属性值:实体类的生成位置 targetPackage属性值:实体类所在包的路径 -->
		<javaModelGenerator
			targetPackage="org.lanqiao.entity" targetProject=".\src">
			<!-- trimStrings属性值: true:对数据库的查询结果进行trim操作 false(默认):不进行trim操作 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<!-- targetProject属性值:SQL映射文件的生成位置 targetPackage属性值:SQL映射文件所在包的路径 -->
		<sqlMapGenerator targetPackage="org.lanqiao.mapper"
			targetProject=".\src">
		</sqlMapGenerator>
		<!-- 生成动态代理的接口 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="org.lanqiao.mapper" targetProject=".\src">
		</javaClientGenerator>
		<!-- 指定数据库表 -->
		<table tableName="student">
		</table>
		<table tableName="studentcard">
		</table>
		<table tableName="studentclass">
		</table>
	</context>
</generatorConfiguration>

测试文件:

public class Test {
public static void main(String[] args) {
        File file = new File("配置文件的位置/generator.xml") ;//配置文件
        List<String> warnings = new ArrayList<>() ;
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(file);
    	DefaultShellCallback callBack = new DefaultShellCallback(true);
		//逆向工程的核心类
		MyBatisGenerator generator = new MyBatisGenerator(config, callBack , warnings)
		generator.generate( nu1l);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值