0


IDEA搭建SSM框架


一、新建项目

1.新建maven项目

2.点击Next,填写GroupId、ArtifactId

groupId一般是域名的反写,也作为项目中类的包名,artifactId是工程名,也就是根文件夹名

3.点击Next,配置路径

Maven home directory选择maven本地安装路径;

勾上User setting file 的 Override前的√,选择本地maven安装的settings.xml配置文件路径

4.继续next,选择项目保存的位置

5.构建项目目录

  • main 右击选择 Directory 创建 java 和 resources两个文件;
  • 再后点击右上角(画箭头号)处,弹出该界面;
  • 选择java点击Sources,选择resources点击Resources,之后Apply点击OK;

创建时可以直接选择提示的

如果新建的目录没有图标就需要设置目录源

成功后的图标:

二、配置文件

1.pom.xml配置

<?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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.springmvc</groupId>
  <artifactId>hellobeijing</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>hellobeijing Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://maven.apache.org</url>

  <properties>
    <!-- spring版本号 -->
    <spring.version>4.2.5.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.2.4</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
  </properties>
  <dependencies>
    <!-- spring核心包 -->
    <!-- springframe start -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- springframe end -->

    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- mysql驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.29</version>
    </dependency>
     <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!-- junit测试包 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
      <scope>provided</scope>
    </dependency>

    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <!-- json数据 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.1</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>
    <!-- commons -->
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>commons-pool</groupId>
      <artifactId>commons-pool</artifactId>
      <version>1.5.6</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.8.3</version>
    </dependency>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <version>1.0</version>
    </dependency>

    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!--上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <!-- log end -->
  </dependencies>
  <build>
    <finalName>helloworld</finalName>
    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <!--允许移动生成的文件-->
          <verbose>true</verbose>
          <!--允许覆盖生成的文件-->
          <overwrite>true</overwrite>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

2.jdbc.properties配置

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/17bang?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234
#最大连接数
maxPoolSize=20
#最小连接数
minPoolSize=10
#连接超时时间
checkoutTimeout=60000
#失败重连次数
acquireRetryAttempts=3

3.mybatis-config.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="jdbcTypeForNull" value="NULL"/>

        <!--显式的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题  -->
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>

        <!-- 使⽤jdbc的getGeneratedKeys获取数据库⾃增主键值 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 使⽤列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

4.applicationContext.xml配置

<?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"
       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/tx
       http://www.springframework.org/schema/tx/springtx.xsd">

        <!--配合MyBatis-->
        <!--配置数据库参数-->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <!--数据库连接池-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <!--配置连接池属性-->
                <property name="driverClass" value="${jdbc.driver}"/>
                <property name="jdbcUrl" value="${jdbc.url}"/>
                <property name="user" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
                <!--c3p0连接池私有属性-->
                <property name="maxPoolSize" value="${maxPoolSize}"/>
                <property name="minPoolSize" value="${minPoolSize}"/>
                <property name="autoCommitOnClose" value="false"/>
                <property name="checkoutTimeout" value="${checkoutTimeout}"/>
                <property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
        </bean>

        <!-- 配置 SqlSessionFactory 对象,spring和MyBatis完美整合,不需要mybatis的配置映射文件-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!--注入数据库连接池-->
                <property name="dataSource" ref="dataSource"/>
                <!-- 配置 MyBaties 全局配置⽂件:mybatis-config.xml -->
                <property name="configLocation" value="classpath:mybatis-config.xml"/>
                <!-- 扫描 model 包 使⽤别名 -->
                <property name="typeAliasesPackage" value="com.springmvc.entity"/>
                <!-- 扫描 sql 配置⽂件:mapper 需要的 xml ⽂件 -->
                <property name="mapperLocations" value="classpath:mappers/*.xml"/>
        </bean>
        <!-- 配置扫描 dao 接⼝包, 动态实现 dao 接⼝, 注⼊到 Spring 容器中 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <!-- 注⼊ sqlSessionFactory -->
                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
                <!-- 给出需要扫描 dao 接⼝包 -->
                <property name="basePackage" value="com.springmvc.dao"/>
        </bean>
        <!--spring-service-->
        <!-- 扫描 service 包下所有使⽤注解的类型 -->
        <context:component-scan base-package="com.springmvc.service"/>

        <!-- 配置事务管理器 -->
        <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <!-- 注⼊数据库连接池 -->
                <property name="dataSource" ref="dataSource"/>
        </bean>
</beans>

5. dispatcherServlet.xml配置

也可能叫 spring-mvc.xml

<?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:p="http://www.springframework.org/schema/p"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- controller扫描器 -->
    <context:component-scan base-package="com.springmvc.controller"/>

    <!-- 配置注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--静态资源默认servlet配置
        (1)加⼊对静态资源的处理: js,gif,png
        (2)允许使⽤"/"做整体映射
    -->
    <mvc:default-servlet-handler/>
</beans>

6.web.xml配置

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!--Spring MVC 配置 并添加监听-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>

    <!-- 字符过滤器 传值乱码-->
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置前端控制器 进行请求分发 DispatcherServlet本质也是一个Servlet -->
    <servlet>
        <!--名字可以自定义-->
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcherServlet.xml</param-value>
        </init-param>
        <!--标记容器启动的时候就启动这个servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!--拦截所有-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

三.配置log4j日志

1.pom.xml配置

上面 pom.xml 已经添加了

   <properties>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
  </properties
    <dependencies>
    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    </dependencies>

2.log4j.properties配置

### set log levels ###
log4j.rootLogger = INFO,D

###输出到控制台###
log4j.logger.toConsole=debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n

### 输出到日志文件 ###
##  其中File 可以采用绝对路径 亦可以采用相对路径 catalina.home 是tomcat目录  如果没有logs文件夹 将会报错  ##
##  更加倾向于将日志文件放在  D:/database/log4j/log4jTest/logtest.log ##
##  绝对路径如:e:/logtest.log ##
log4j.logger.daily=INFO,D
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D:/database/log4j/log4jTest/logtest.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n

##log4j.logger.org.apache.ibatis=debug,stdout
##log4j.logger.java.sql=debug,stdout

四.mybatis逆向工程

Mybatis-Generator自动生成Dao、Model层相关代码

1.pom.xml配置

注意:mybatis-generator-maven-plugin 插件的plugins标签要与pluginManagement标签并列,不然在右边Maven中找不到该插件


<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.5</version>
    </dependency>

<!--注意:mybatis-generator-maven-plugin  插件的plugins标签要与</pluginManagement>并列-->
<plugins>
      <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>

2.generatorConfig.xml配置

classPathEntry 标签值根据本地位置修改

第一个(推荐)
<?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>

    <!--导入属性配置 jdbc配置文件-->
    <properties resource="jdbc.properties"></properties>
<!--
        targetRuntime: 执行生成的逆向工程的版本
                MyBatis3Simple: 生成基本的CRUD(清新简洁版)
                MyBatis3: 生成带条件的CRUD(奢华尊享版)
 -->
<context id="DB2Tables" targetRuntime="MyBatis3">
    <!--jdbc的数据库连接 -->
    <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}"
                    userId="${jdbc.username}" password="${jdbc.password}">
    </jdbcConnection>
    <!-- javaBean的生成策略-->
    <javaModelGenerator targetPackage="com.springmvc.entity" targetProject="./src/main/java">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!-- SQL映射文件的生成策略 -->
    <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
        <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    <!-- Mapper接口的生成策略 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.springmvc.dao" targetProject="./src/main/java">
        <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
    <!-- 逆向分析的表 -->
    <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
    <!-- domainObjectName属性指定生成出来的实体类的类名 -->
    <table tableName="user" domainObjectName="User" >
    </table>

</context>
</generatorConfiguration>

第二个

<?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>
    <!--导入属性配置 jdbc配置文件-->
    <properties resource="jdbc.properties"></properties>

    <!--指定特定数据库的jdbc驱动jar包的位置  此处需要指明mysql-connector-java-5.1.30.jar的绝对路径,否则会报错!-->
    <classPathEntry location="D:\Application\IDEA\repository\mysql\mysql-connector-java\8.0.11\mysql-connector-java-8.0.11.jar"/>

    <context id="default" targetRuntime="MyBatis3">

        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}"
                        userId="${jdbc.username}" password="${jdbc.password}">
        </jdbcConnection>

        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成模型model的包名和位置 此处需要根据自己项目做调整-->
        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
      targetPackage     指定生成的model生成所在的包名
        targetProject     指定在该项目下所在的路径
    -->
        <!--<javaModelGenerator targetPackage="com.mmall.pojo" targetProject=".\src\main\java">-->
        <javaModelGenerator targetPackage="com.springmvc.entity" targetProject="./src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 (去空)-->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
            type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
            type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
            type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
   -->

        <!-- targetPackage:mapper接口dao生成的位置 -->
        <!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject=".\src\main\java">-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.springmvc.dao" targetProject="./src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
        <table tableName="user" domainObjectName="User" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
            <!-- 数据库中该字段的类型是 txt ,不同版本生成对应字体类的属性类型可能不同,因此指定转换类型 -->

        <!-- mybatis插件的搭建 -->
    </context>
</generatorConfiguration>

3.找到 Maven ----> …Webapp -----> Plugins -----> mybatis-generator

(注!!!:这里有时候会发现没有该插件,这时是pom.xml中mybatis-generator-maven-plugin 插件的plugins标签要与pluginManagement标签并列)

-----> mybatis-generator:generate -----> 右击 选择 Run Maven Build

生成的文件:

五、开发

1.数据库

use 17bang;
create table `user`(
    id INT(11),
    `name` VARCHAR(25),
    age INT(11)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
select * from `user`;
insert into  `user` (id,`name`,age) values(1,'张三',20),(2,'李四',18);

2.UserService.java

package com.springmvc.service;

import com.springmvc.dao.UserMapper;
import com.springmvc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User getUserById(Integer id){
        return userMapper.selectByPrimaryKey(id);
    }

}

3.UserController.java

package com.springmvc.controller;

import com.springmvc.entity.User;
import com.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value="/getUser",method = RequestMethod.GET)
    @ResponseBody
    public User getUser(Integer id){
        User user = userService.getUserById(id);
        return user;
    }
}

可能报错:

有时候 private UserService userService 加上 @Autowired 会报编译错误,

解决方案:

找到该页面,将 Autowiring for Bean Class √去掉,Apply OK

六.配置Tomcat

1.添加tomcat

最好选择 tomcat7

2.配置Tomcat服务器页签

  • Name:tomcat命名;
  • Application server:选中本地安装目录;
  • JRE:选中本地安装的jdk路径

3.部署页签

点击 Deployment (部署)进入该页面

点击 ‘+’

选中“…:war exploded”;

Application context 可以修改项目访问路径的项目名,如:http://localhost:8080/ssm

4.Apply OK 之后,Tomcat 配置成功;

七.测试

八、可能出现的问题

1.tomcat控制台乱码

解决方案:

1.新增一行

-Dfile.encoding=UTF-8

2.如果1没有解决

setting修改编码


3. 配置tomcat

2.启动 tomcat 出错 / 访问地址404 / 配置应用程序监听器[org.springframework.web.context.ContextLoaderListener]错误

将 tomcat10 换成 tomcat7

3.Mybatis异常“Cannot enable lazy loading because CGLIB is not available. Add CGLIB to your classpath.”

缺少CGLIB,添加依赖到工程中,打开Pom文件,添加依赖

    <!-- cglib -->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>3.2.5</version>
    </dependency>

4.mysql 连接错误 No suitable driver

### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: 
Could not get JDBC Connection; nested exception is java.sql.SQLException: 
Connections could not be acquired from the underlying database!] with root cause
java.sql.SQLException: No suitable driver

解决方案:

将 mysql-connector-java-8.0.16.jar包 添加到 jre

完成

将 mysql-connector-java-8.0.16.jar包移动到自己配置系统环境变量的jdk文件下的jre文件中

路径如下:jdk1.8.0_261——>jre——>lib——>ext

ps:下载 mysql 驱动

MySQL :: MySQL Community Downloads

选择平台无关

下载

5.配置了视图解析器之后,如何跳到初始的index.jsp

//方法一

@RequestMapping("/returnIndex")
public String returnIndex(){
    return "redirect:/index.jsp";
}

//方法二
@RequestMapping("/returnIndex2")
public void returnIndex2(HttpServletResponse response) throws Exception{
    response.sendRedirect("/index.jsp");
}

6.设置IDEA修改html、jsp后立即生效,不用重启项目

原文:设置IDEA修改html、jsp后立即生效,不用重启项目_idea里的项目如何不需要重新构建_技匠而已的博客-CSDN博客

7.前后端数据交互

菜鸟学SpringMVC之——SpringMVC执行原理、向前端返回数据的三种方式_springmvc返回数据给前端_菜鸟琪的博客-CSDN博客

标签: intellij-idea java ide

本文转载自: https://blog.csdn.net/weixin_62013325/article/details/131178588
版权归原作者 Show my bug 所有, 如有侵权,请联系我们删除。

“IDEA搭建SSM框架”的评论:

还没有评论