一步一步教你用IntelliJ IDEA 搭建SSM框架(2)——配置mybatis-geneator


我們要搭建整個SSM框架,所以要繼續上篇文章沒有完成的工作,下面配置mybatis-geneator,自動生成mybatis代碼。

在上篇文章中的pom.xml的配置文件中已經加了mybatis-geneator的依賴包,如下圖:

請注意:上圖的plugins是和pluginManagement是同級的,如果把mybatis.geneator的plugin放在pluginManagement就引用不到mybatis-geneator

 

然后在 applicationContext.xml文件中添加下面代碼:

<!-- 配置會話工廠SqlSessionFactory -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:sqlmap/*Mapper.xml"/>
        <property name="typeAliasesPackage" value="cn.only.entity" />

    </bean>

    <!-- 在spring容器中配置mapper的掃描器產生的動態代理對象在spring的容器中自動注冊,bean的id就是mapper類名(首字母小寫)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定掃描包的路徑,就是mapper接口的路徑,多個包中間以 半角逗號隔開   -->
        <property name="basePackage" value="cn.only.dao"/>
        <!-- 配置sqlSessionFactoryBeanName -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
View Code

 

 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"/>

    <classPathEntry
            location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.0.8\mysql-connector-java-5.0.8.jar" />
    <context id="context1">
        <!-- 注釋 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消注釋 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注釋代時間戳 -->
        </commentGenerator>

        <jdbcConnection driverClass="${driver}"
                        connectionURL="${url}"
                        userId="${username}"
                        password="${password}" />

        <!-- 類型轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}"
                            targetProject="${modelProject}" />
        <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
        <javaClientGenerator targetPackage="${mapperPackage}"
                             targetProject="${mapperProject}" type="XMLMAPPER" />

        <!-- 如果需要通配所有表 直接用sql的通配符    %即可 -->
        <table schema="" tableName="${table}" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"/>

    </context>
</generatorConfiguration>
View Code

代碼中的classPathEntry的location換成您本地的。如下圖,

注意:如果mysql-connector-java的版本與本地的MySQL版本不配套,數據庫操作會報錯。

 generator.properties配置

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username=root
password=******

#entity 包名和 java目錄
modelPackage=cn.only.entity
modelProject=src/main/java
#sqlmap包名 和resources目錄
sqlPackage=sqlmap
sqlProject=src/main/resources
#mapper包名和 java目錄
mapperPackage=cn.only.dao
mapperProject=src/main/java

table=message
View Code

注意:上面的代碼中如果沒有serverTimezone=UTC,代碼運行會報錯

modelPackage:連接數據庫自動生成的實體類保存的位置

sqlPackage:生成xml映射文件保存的位置

mapperPackage:生成數據庫接口保存的位置

table:數據庫里面表的名字

現在mybatis-geneator已經配置好了。

MySQL數據庫中已經建立了數據庫test和表message。

點擊IntelliJ IDEA右側邊欄的Maven Projects,如下圖。

雙擊上圖中的 mybatis-generator:generate,運行結果如下圖

 

 

mybatis-generator運行成功以后會自動生成以下文件:

 

 現在Spring MVC + Spring + MyBatis 的框架已經搭建好,下面就用junit測試工具,測一下數據能不能正常寫入數據庫。

打開MessageMapper文件,添加@Repository標簽,表明這是數據訪問組件,如下圖

上圖中鼠標放在緊跟在MessageMapper后面,按alt+enter,選擇Create Test,彈窗如下圖:

上圖中選中insert,點擊OK,會在test目錄下生成MessageMapperTest測試文件,測試代碼就寫在此文件中如下:

package cn.only.dao;

import cn.only.entity.Message;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class MessageMapperTest {
    private ApplicationContext applicationContext;

    @Autowired
    private MessageMapper mapper;
    @Before
    public void setUp() throws Exception {
        // 加載spring配置文件
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        // 導入需要測試的
        mapper = applicationContext.getBean(MessageMapper.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void insert() throws Exception{
        Message message = new Message();
        message.setCommand("做仙女");
        message.setContent("吃美食");
        message.setDescription("雲游四方");
        int result = mapper.insert(message);
        System.out.println(result);
        assert (result == 1);
    }
}
View Code

如上圖點擊綠色圓圈和三角形組合,點擊Run ‘insert()’,運行結果如下,表示運行成功。

 

打開數據庫查看結果如下:

好了,SSM框架已經搭建成功。

本文參照這篇文章寫的:https://www.cnblogs.com/toutou/p/9015126.html#_nav_0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM