美文网首页
IntellJ IDEA使用及配置杂记

IntellJ IDEA使用及配置杂记

作者: Tod_2021 | 来源:发表于2022-07-30 15:17 被阅读0次

    前言

    本人项目多用Java语言开发,且IDE主要是IntelliJ IDEA2019.1 x64版本,由于在IDEA工具的使用上,本人有时也是一知半解,遇到问题就百度搜索,然而网上很多资料参差不齐,故想着将自己遇到的问题整理总结,希望能对你有所帮助,我尽量会整理详细些,如有不懂或描述不恰当的地方,请留言指出,谢谢~

    问题一:Maven项目JDK与本机JDK版本不一致

    描述:本人安装的JDK版本是1.8,每当我创建一个Maven工程后,项目的默认JDK版本默认是1.5,而且每次我重新打开项目或者挂着项目没操作后,即使更改为JDK1.8也会被默默改回JDK1.5。出现问题如下:

    Lambda表达式无法使用 编译时程序报错

    下面介绍两种方法解决,第一种比较笨且为临时的,第二种较好。

    解决方法一:修改项目JDK版本

    1. 打开Settings窗口(快捷键Ctrl + Alt + S):File -> Settings
    Setting窗口修改Java Compiler

    修改JDK版本为8

    1. 打开Project Structure窗口(快捷键Ctrl + Alt + Shift + S):File -> Project Structure
    Project JDK版本是否对应 Modules source的JDK是否对应

    逐一修改每个项目的JDK版本,Apply即可解决

    存在不足:临时性修改,下一次重启有可能会出现版本不一致问题

    解决方法二:pom文件约定JDK版本

    在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">
        <properties>
            <java.version>1.8</java.version>
            <maven.version>3.5.1</maven.version>
        </properties>
        <build>
            <plugins>
                <!--调整modules的language level为8-->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.version}</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    <project></project>都贴上了,免得你不知道放在哪里,嘿嘿

    如果你的项目是多个模块,那么只需要在主模块中添加

    可以一劳永逸解决

    问题二:如何生成IDEA自定义代码模板

    例如上一个问题中的代码块,如果每次使用时,都需要找到对应的代码进行复制粘贴,很繁琐,好在IDEA提供了一个Live Templates功能,能够自定义代码模板,只需要输入相应的快捷方式就能自动生成,类似于psvmIDEA就能自动填充为public static void main(String[] args)一样。

    • 打开Settings窗口(快捷键Ctrl + Alt + S):File -> Settings
    Editor下的Live Templates
    • 创建一个Template Group
    创建Template Group
    • 在新建的Template Group下创建Live Template
    创建Live Template
    • 创建Live Template
    创建Live Template

    其中maven_jdk_setting类似于psvm,设置作用在xml文件中

    • 效果图如下:
    快捷方式生成自定义代码模块 效果图

    个人常用模板

    • 热部署插件(devtools_build)

      <build>
          <plugins>
              <plugin>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-maven-plugin</artifactId>
                  <configuration>
                      <fork>true</fork>
                  </configuration>
              </plugin>
          </plugins>
      </build>
      
    • JPA对应的persistence_xml的文件格式(jpa_persistence_xml)

      <?xml version="1.0" encoding="UTF-8"?>
      <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
          <!--需要配置persistence-unit节点
              持久化单元:
                  name:持久化单元名称
                  transaction-type:事务管理的方式
                          JTA:分布式事务管理
                          RESOURCE_LOCAL:本地事务管理
          -->
          <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
              <!--jpa的实现方式 -->
              <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
      
              <!--可选配置:配置jpa实现方的配置信息-->
              <properties>
                  <!-- 数据库信息
                      用户名,javax.persistence.jdbc.user
                      密码,  javax.persistence.jdbc.password
                      驱动,  javax.persistence.jdbc.driver
                      数据库地址   javax.persistence.jdbc.url
                  -->
                  <property name="javax.persistence.jdbc.user" value="root"/>
                  <property name="javax.persistence.jdbc.password" value="root"/>
                  <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
                  <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///db1"/>
      
                  <!--配置jpa实现方(hibernate)的配置信息
                      显示sql           :   false|true
                      自动创建数据库表    :  hibernate.hbm2ddl.auto
                              create      : 程序运行时创建数据库表(如果有表,先删除表再创建)
                              update      :程序运行时创建表(如果有表,不会创建表)
                              none        :不会创建表
      
                  -->
                  <property name="hibernate.show_sql" value="true" />
                  <property name="hibernate.hbm2ddl.auto" value="update" />
              </properties>
          </persistence-unit>
      </persistence>
      
    • mybatis的application配置yml文件(mybatis_applicaiton_yml)

      # 数据源配置
      spring:
        datasource:
          # url username password TODO
          url: jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf8
          username: 用户名
          password: 密码
          driver-class-name: com.mysql.jdbc.Driver
      # MyBatis配置
      mybatis:
        # type-aliases-package mapper-locations TODO
        type-aliases-package: cn.tod.mybatisgenerator.entity
        mapper-locations: classpath:cn.tod.mybatisgenerator.mapper/*.xml
      
      # mybatis.config = mybatis 配置⽂件名称
      # mybatis.mapperLocations = mapper xml ⽂件地址 #
      # mybatis.typeAliasesPackage = 实体类包路径
      # mybatis.typeHandlersPackage = type handlers 处理器包路径
      # mybatis.check-config-location = 检查 mybatis 配置是否存在,⼀般命名为 mybatis-config.xml
      # mybatis.executorType = 执⾏模式。默认是 SIMPLE
      
    • mybatis对应的config_xml文件格式(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>
          <!-- 配置 mybatis 的环境 -->
          <environments default="mysql">
              <!-- 配置 mysql 的环境 -->
              <environment id="mysql">
                  <!-- 配置事务的类型 -->
                  <transactionManager type="JDBC"></transactionManager>
                  <!-- 配置连接数据库的信息:用的是数据源(连接池) -->
                  <dataSource type="POOLED">
                      <property name="driver" value="com.mysql.jdbc.Driver"/>
                      <property name="url" value="jdbc:mysql://localhost:3306/数据库名"/>
                      <property name="username" value="用户名"/>
                      <property name="password" value="密码"/>
                  </dataSource>
              </environment>
          </environments>
          <!-- 告知 mybatis 映射配置的位置:基于xml配置 -->
          <mappers>
              <mapper resource="cn/tod/mybatis/dao/IUserDao.xml"/>
              <!-- <mapper class="cn.tod.mybatis.dao.IUserDao"/> -->
          </mappers>
      </configuration>
      
    • mybatis对应的config_xml文件配置(基于注解配置)(mybatis_config_xml_annotation)

      <?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>
          <!-- 配置 mybatis 的环境 -->
          <environments default="mysql">
              <!-- 配置 mysql 的环境 -->
              <environment id="mysql">
                  <!-- 配置事务的类型 -->
                  <transactionManager type="JDBC"></transactionManager>
                  <!-- 配置连接数据库的信息:用的是数据源(连接池) -->
                  <dataSource type="POOLED">
                      <property name="driver" value="com.mysql.jdbc.Driver"/>
                      <property name="url" value="jdbc:mysql://localhost:3306/数据库名"/>
                      <property name="username" value="用户名"/>
                      <property name="password" value="密码"/>
                  </dataSource>
              </environment>
          </environments>
          <!-- 告知 mybatis 映射配置的位置:基于注解配置,需要删除对应的mapper.xml -->
          <mappers>
              <mapper class="cn.tod.mybatis.dao.IUserDao"/>
          </mappers>
      </configuration>
      
    • mybatis对应的mapper_xml文件格式(mybatis_mapper_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="cn.tod.mybatis.dao.IUserDao">
          <select id="findAll" resultType="cn.tod.mybatis.entity.User">
              SELECT * FROM user
          </select>
      </mapper>
      
    • mybatisgenerator的pom插件(mybatisgenerator_build_pom_xml)

      <build>
          <plugins>
              <plugin>
                  <groupId>org.mybatis.generator</groupId>
                  <artifactId>mybatis-generator-maven-plugin</artifactId>
                  <version>1.3.2</version>
                  <configuration>
                      <!--其中generatorConfig.xml的位置,大家根据实际情况自行调整-->
                      <configurationFile>src/main/resources/MybatisGeneratorConfig.xml</configurationFile>
                      <verbose>true</verbose>
                      <overwrite>true</overwrite>
                  </configuration>
                  <executions>
                      <execution>
                          <id>Generate MyBatis Artifacts</id>
                          <goals>
                              <goal>generate</goal>
                          </goals>
                      </execution>
                  </executions>
                  <dependencies>
                      <dependency>
                          <groupId>org.mybatis.generator</groupId>
                          <artifactId>mybatis-generator-core</artifactId>
                          <version>1.3.2</version>
                      </dependency>
                      <dependency>
                          <groupId>mysql</groupId>
                          <artifactId>mysql-connector-java</artifactId>
                          <version>5.1.47</version>
                      </dependency>
                  </dependencies>
              </plugin>
          </plugins>
      </build>
      
    • mybatisgenerator的配置文件(mybatisgenerator_config_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"> <!-- 手动导入mybatis-generator-config_1_0.dtd-->
      <!--因为生成过程中需要连接db,所以第3行指定了驱动jar包的位置-->
      <generatorConfiguration>
          <!--    <classPathEntry-->
          <!--            location="C:/Oracle/Middleware/wlserver_10.3/server/lib/ojdbc6.jar"/>-->
          <context id="my" targetRuntime="MyBatis3">
              <!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
              <property name="javaFileEncoding" value="UTF-8"/>
              <commentGenerator>
                  <property name="suppressDate" value="false"/>
                  <property name="suppressAllComments" value="true"/>
              </commentGenerator>
      
              <!-- oracle配置 -->
              <!--             <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
                          connectionURL="jdbc:oracle:thin:@***:1521:orcl" userId="***"
                          password="***">
                          针对oracle数据库
                          <property name="remarksReporting" value="true"></property>
                      </jdbcConnection> -->
      
              <!-- mysql配置 -->
              <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                              connectionURL="jdbc:mysql://localhost:3306/数据库名?useUnicode=true"
                              userId="用户名"
                              password="密码"><!--connectionURL userId password TODO-->
                  <!-- 针对mysql数据库 -->
                  <property name="useInformationSchema" value="true"></property>
              </jdbcConnection>
              <javaTypeResolver>
                  <property name="forceBigDecimals" value="false" />
              </javaTypeResolver>
      
              <!--19-33行指定生成“entity实体类、mybatis映射xml文件、mapper接口”的具体位置-->
              <javaModelGenerator targetPackage="cn.tod.mybatisgenerator.entity"
                                  targetProject="src\main\java"><!--targetPackage TODO-->
                  <property name="enableSubPackages" value="true"/>
                  <property name="trimStrings" value="true"/>
              </javaModelGenerator>
      
              <sqlMapGenerator targetPackage="cn.tod.mybatisgenerator.mapper"
                               targetProject="src\main\resources"><!--targetPackage TODO-->
                  <property name="enableSubPackages" value="true"/>
              </sqlMapGenerator>
      
              <javaClientGenerator targetPackage="cn.tod.mybatisgenerator.mapper"
                                   targetProject="src\main\java" type="XMLMAPPER"><!--targetPackage TODO-->
                  <property name="enableSubPackages" value="true"/>
              </javaClientGenerator>
      
      
              <!--40-46行为具体要生成的表,如果有多个表,复制这一段,改下表名即可-->
              <table tableName="userinfo" domainObjectName="UserInfo"
                     enableCountByExample="false" enableUpdateByExample="false"
                     enableDeleteByExample="false" enableSelectByExample="false"
                     selectByExampleQueryId="false"><!--tableName domainObjectName TODO-->
              </table>
          </context>
      </generatorConfiguration>
      
    • spring基于aop的bean_xml文件格式(spring_aop_bean_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: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/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd">
          <!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
                  id 属性:对象的唯一标识。
                  class 属性:指定要创建对象的全限定类名
                  -->
          <!-- 配置 service -->
          <bean id="accountService" class="cn.tod.spring.aop.xml.service.impl.AccountServiceImpl">
              <property name="IAccountDao" ref="accountDao"/>
          </bean>
          <!-- 配置 dao -->
          <bean id="accountDao" class="cn.tod.spring.aop.xml.dao.impl.AccountDaoImpl">
              <property name="queryRunner" ref="queryRunner"/>
              <property name="connectionUtils" ref="connectionUtils"/>
          </bean>
          <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>
          <bean id="connectionUtils" class="cn.tod.spring.aop.xml.utils.ConnectionUtils">
              <property name="threadLocal" ref="threadLocal"/>
              <property name="dataSource" ref="dataSource"/>
          </bean>
          <bean id="threadLocal" class="java.lang.ThreadLocal"/>
          <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="com.mysql.jdbc.Driver"/>
              <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db1"/>
              <property name="user" value="root"/>
              <property name="password" value="root"/>
          </bean>
      
          <!-- 配置通知 -->
          <bean id="transactionManager" class="cn.tod.spring.aop.xml.utils.TransactionManager">
              <property name="connectionUtils" ref="connectionUtils"/>
          </bean>
          <!-- 使用aop:config声明aop配置 -->
          <aop:config>
      <!--        &lt;!&ndash; 使用aop:aspect配置切面 &ndash;&gt;-->
      <!--        <aop:aspect id="transactionAdvice" ref="transactionManager">-->
      <!--            &lt;!&ndash; 使用aop:before配置前置通知 &ndash;&gt;-->
      <!--            <aop:before method="beginTransaction" pointcut-ref="pc1"/>-->
      <!--            &lt;!&ndash; 使用aop:pointcut配置切入点表达式 &ndash;&gt;-->
      <!--            &lt;!&ndash; * 代表任意 返回值、包、类名、数据类型, ..可以表示参数列表有无参数均可、当前包及其子包 &ndash;&gt;-->
      <!--&lt;!&ndash;            <aop:pointcut id="pc1" expression="execution(&ndash;&gt;-->
      <!--&lt;!&ndash;                public void cn.tod.spring.aop.xml.service.impl.AccountServiceImpl.transfer(&ndash;&gt;-->
      <!--&lt;!&ndash;                    java.lang.String, java.lang.String, java.lang.Double&ndash;&gt;-->
      <!--&lt;!&ndash;                )&ndash;&gt;-->
      <!--&lt;!&ndash;            )"/>&ndash;&gt;-->
      <!--            <aop:pointcut id="pc1" expression="execution(-->
      <!--                * cn.tod.spring.aop.xml.service.impl.*.*(..)-->
      <!--            )"/>-->
      <!--            &lt;!&ndash; 使用aop:after-returning配置后置通知 &ndash;&gt;-->
      <!--            <aop:after-returning method="commit" pointcut-ref="pc1"/>-->
      <!--            &lt;!&ndash; 使用aop:after-throwing配置异常通知 &ndash;&gt;-->
      <!--            <aop:after-throwing method="rollback" pointcut-ref="pc1"/>-->
      <!--            &lt;!&ndash; 使用aop:after配置最终通知 &ndash;&gt;-->
      <!--            <aop:after method="release" pointcut-ref="pc1"/>-->
      <!--        </aop:aspect>-->
              <aop:pointcut id="pc1" expression="execution(
                  * cn.tod.spring.aop.xml.service.impl.*.*(..)
              )"/>
              <aop:aspect id="transactionAdvice" ref="transactionManager">
                  <!-- 配置环绕通知 -->
                  <aop:around method="transactionAround" pointcut-ref="pc1"/>
              </aop:aspect>
          </aop:config>
      </beans>
      
    • spring对应的注解方式的bean_xml文件格式(spring_bean_annotation_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">
          <!-- 告知 spring 创建容器时要扫描的包 -->
          <context:component-scan base-package="cn.tod.spring.annotation"/>
          <!-- 配置数据源 -->
          <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="com.mysql.jdbc.Driver"/>
              <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db1"/>
              <property name="user" value="root"/>
              <property name="password" value="root"/>
          </bean>
          <!-- 配置JdbcTemplate -->
          <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
              <property name="dataSource" ref="dataSource"/>
          </bean>
      </beans>
      
    • spring对应的bean_xml文件格式(spring_bean_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"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">
          <!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
                  id 属性:对象的唯一标识。
                  class 属性:指定要创建对象的全限定类名
                  -->
          <!-- 配置 service -->
          <bean id="accountService" class="cn.tod.spring.service.impl.AccountServiceImpl">
              <!-- 给数组注入数据 -->
              <property name="myStrs">
                  <set>
                      <value>AAA</value>
                      <value>bbb</value>
                      <value>CCC</value>
                  </set>
              </property>
              <!-- 注入 list 集合数据 -->
              <property name="myList">
                  <array>
                      <value>DDD</value>
                      <value>eee</value>
                      <value>FFF</value>
                  </array>
              </property>
              <!-- 注入 set 集合数据 -->
              <property name="mySet">
                  <list>
                      <value>GGG</value>
                      <value>GGG</value>
                      <value>hhh</value>
                  </list>
              </property>
              <!-- 注入 Map 数据 -->
              <property name="myMap">
                  <props>
                      <prop key="AAA">aaa</prop>
                      <prop key="BBB">bbb</prop>
                  </props>
              </property>
              <!-- 注入 properties 数据 -->
              <property name="myProps">
                  <map>
                      <entry key="AAA" value="aaa"/>
                      <entry key="BBB">
                          <value>bbb</value>
                      </entry>
                  </map>
              </property>
          </bean>
          <!-- 配置 dao -->
          <bean id="accountDao" class="cn.tod.spring.dao.impl.AccountDaoImpl">
      <!--        <constructor-arg name="name" value="Tod"/>-->
      <!--        <constructor-arg name="age" value="25"/>-->
      <!--        <constructor-arg name="birthday" ref="yesterday"/>-->
              <property name="name" value="Jim"/>
              <property name="age" value="24"/>
              <property name="birthday" ref="yesterday"/>
          </bean>
          <bean id="yesterday" class="java.util.Date"/>
      </beans>
      

    问题三:如何使用IDEA自动生成实体类的serialVersionUID

    有时候我们为了防止实体类在存储中被人为修改,需要实现实体类的序列化机制,实现Serializable接口,同时定义一个唯一的SerializeUID,代码如下:

    import java.io.Serializable;
    
    public class User implements Serializable {
        private static final long serialVersionUID = 2588932577248604962L;
    }
    
    

    serialVersionUID可以自己定义,也可以有IDEA自动生成,只要保证唯一即可

    下面讲一下如何使用IDEA自动生成serialVersionUID

    • 打开Settings窗口(快捷键Ctrl + Alt + S):File -> Settings
    设置中打开生成serialVersionUID警告

    搜索serialize,选择实现Serializable接口的类没有定以serialVersionUID会有警告提示

    • 生成实体类的serialVersionUID
    生成serialVersionUID

    在实体类名称上按下Alt + Enter快捷键

    效果图

    相关文章

      网友评论

          本文标题:IntellJ IDEA使用及配置杂记

          本文链接:https://www.haomeiwen.com/subject/gcgcwrtx.html