maven構建項目,整合ssm(2 整合mybatis)

完整的代碼請見碼雲  https://gitee.com/liuhuxiang/simplemavendemojava

1 下載mysql 

這一步就不詳述了,網上的教程有不少,小夥伴自行參考,有個點要注意下,高版本的mysql下載完成後,用navicat等客戶端鏈接會有錯誤,建議下載4.1.17如下的版本mysql

具體參考: https://blog.csdn.net/sun19910114/article/details/39118045git

建立數據庫web

CREATE DATABASE liuhuxiang;

查詢數據庫spring

show databases;

進入數據庫sql

use liuhuxiang;

建立測試表數據庫

DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(40) NOT NULL,
  `password` varchar(255) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
insert  into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'測試','sfasgfaf',24);

2 pom文件配置

經過maven去下載pom文件中指定的jar,主要包括一些spring的核心包,mybatis,dbcp,以及log4j的包,一次性提供給你們,經過命令 mvn clean install:install下載包,若是發現下載速度太慢的話,就去用阿里雲鏡像,享受飛速下載。。。apache

<?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>cn.liuhuxiang</groupId>
  <artifactId>simplemavendemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>simplemavendemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>
    <!-- spring版本號 -->
    <spring.version>4.0.2.RELEASE</spring.version>
    <!-- mybatis版本號 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日誌文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <!--依賴的jar-->
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- spring核心包 -->
    <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>
    <!-- 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>
    <!-- 導入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!-- 導入Mysql數據庫連接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- JSTL標籤類 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- 日誌文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>


    <!-- 格式化對象,方便輸出日誌 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.41</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>
    <!-- log end -->
    <!-- 映入JSON -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</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>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>
  </dependencies>

  <build>
    <resources>
    <!-- maven項目中src源代碼下的xml等資源文件編譯進classes文件夾, 注意:若是沒有這個,它會自動搜索resources下是否有mapper.xml文件, 若是沒有就會報org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.pet.mapper.PetMapper.selectByPrimaryKey-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <!--將resources目錄下的配置文件編譯進classes文件  -->
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
  </build>
</project>

3 構建包結構

我這裏把個人包結構都提供出來了,你們能夠參考建一下json

這裏可能會出現的問題,就是右鍵,new 的時候,沒有java class這個選項?api

這是由於構建完maven項目的時候,沒有把src下的目錄標註成可編譯的目錄,網上找了篇博客,你們參考下,配置一下就能夠了 

https://blog.csdn.net/qq_27093465/article/details/52912444

4 使用MyBatis Generator構建代碼

推薦的神器,構建代碼十分方便,按照下面的地址操做便可,把構建好的代碼粘貼過來

https://blog.csdn.net/zhshulin/article/details/23912615

可是這裏有個點要注意,就是構建出來的代碼,是按照代碼生成器的目錄層級存放的,咱們生成代碼以後,要按照本身的目錄層級存放,而且把Mapper.xml 裏面對應的東西改掉,不然在測試mybatis的時候,會報各類奇葩的錯誤

這三份文件 UserMaper  User  UserMapper.xml 就是代碼生成器生成的,重點要注意的是UserMapper.xml,這裏很容易出錯,下面用紅線標出來的,要特別注意,改爲本身對應的路徑名稱

UserMaper

package com.liuhuxiang.dao;
import com.liuhuxiang.entity.User;
import org.springframework.stereotype.Component;
/**
 * @author liuhuxiang
 * @version $Id: UserMapper.java, v 0.1 2018年04月19日 15:46 liuhuxiang Exp $
 */
@Component
//把UserMapper註冊成bean
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(User record);
    int insertSelective(User record);
    User selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
}

User

package com.liuhuxiang.entity;
/**
 * @author liuhuxiang
 * @version $Id: User.java, v 0.1 2018年04月19日 15:44 liuhuxiang Exp $
 */
public class User {
    private Integer id;
    private String userName;
    private String password;
    private Integer age;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

UserMapper.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.liuhuxiang.dao.UserMapper" >

  <resultMap id="BaseResultMap" type="com.liuhuxiang.entity.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, user_name, password, age
  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user_t
    where id = #{id,jdbcType=INTEGER}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user_t
    where id = #{id,jdbcType=INTEGER}
  </delete>

  <insert id="insert" parameterType="com.liuhuxiang.entity.User" >
    insert into user_t (id, user_name, password,
      age)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
      #{age,jdbcType=INTEGER})
  </insert>

  <insert id="insertSelective" parameterType="com.liuhuxiang.entity.User" >
    insert into user_t
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="age != null" >
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.liuhuxiang.entity.User" >
    update user_t
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <update id="updateByPrimaryKey" parameterType="com.liuhuxiang.entity.User" >
    update user_t
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>

</mapper>

5 整合mybats,配置文件

這步主要是配置jdbc.properties   log4j.properties   spring-mybatis.xml三個文件

jdbc.properties

主要是數據庫鏈接的常量設置

# 1 這裏必定要注意,看看後面是否有空格,要統一去掉,不然調試會報錯
# 2 localhost若是不行的話,能夠換成127.0.0.1 試試看,liuhuxiang爲數據庫名,以前傻乎乎的覺得是表名=-=
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/liuhuxiang
username=root
password=admin
#定義初始鏈接數
initialSize=0
#定義最大鏈接數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000

log4j.properties

主要是日誌的配置項,經過apache的開源項目Log4j,能夠查看調試過程當中的日誌,很是好用

#這裏你們直接copy就能夠了,沒有什麼要改動的
#定義LOG輸出級別
log4j.rootLogger=INFO,Console,File  
#定義日誌輸出目的地爲控制檯
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
#文件大小到達指定尺寸的時候產生一個新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定輸出目錄
log4j.appender.File.File = logs/ssm.log  
#定義文件最大大小
log4j.appender.File.MaxFileSize = 10MB  
# 輸出因此日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

spring-mybatis.xml

這也是整合mybatis的關鍵文件

<?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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自動掃描 -->
    <!--若是目錄層級直接是src/main/java,那麼base-package=「**」 就能夠了,不過這樣命名並不規範,不建議這樣作-->
    <context:component-scan base-package="com.liuhuxiang" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <!--這裏的${driver}..就是引用jdbc.preperties中的常量,可以點過去,說明配置是ok的-->
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化鏈接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 鏈接池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 鏈接池最大空閒 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 鏈接池最小空閒 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取鏈接最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml文件 -->
        <!--這裏有的人寫classpath會報錯,能夠寫成classpath* 試試看,小編就是寫classpath一直報錯,因此加上了*-->
        <property name="mapperLocations" value="classpath*:com/liuhuxiang/mapping/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <!--建議value中指定的路徑,都點點看,看看是否是本身要的路徑,不要弄錯了-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.liuhuxiang.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

6 補全service

UserService

package com.liuhuxiang.service;
import com.liuhuxiang.entity.User;

/**
 * @author liuhuxiang
 * @version $Id: UserService.java, v 0.1 2018年04月19日 15:28 liuhuxiang.
 */
public interface UserService {
    public User getUserById(int userId);
}

UserServiceImpl

package com.liuhuxiang.service;
import com.liuhuxiang.dao.UserMapper;
import com.liuhuxiang.entity.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * @author liuhuxiang
 * @version $Id: UserServiceImpl.java, v 0.1 2018年04月19日 15:29 liuhuxiang
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public User getUserById(int userId) {
        System.out.println("************************userId=" + userId);
        return this.userMapper.selectByPrimaryKey(userId);
    }
}

7 測試

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="userService" class="com.liuhuxiang.service.UserServiceImpl"/>
</beans>

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration

這兩個標籤不明白的,你們參考下面博客

https://blog.csdn.net/u013803262/article/details/52253825

TestMybatis

package src.test.java.testmybatis;
import com.alibaba.fastjson.JSON;
import com.liuhuxiang.entity.User;
import com.liuhuxiang.service.UserService;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * @author liuhuxiang
 * @version $Id: TestMybatis.java, v 0.1 2018年04月25日 21:55 liuhuxiang Exp $
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml", "classpath*:spring-mybatis.xml"})
public class TestMybatis {
    
    private static Logger      logger = Logger.getLogger(TestMybatis.class);
    @Resource
    private        UserService userService;

    @Test
    public void testMyBatis() {
        User user = userService.getUserById(1);
        logger.info(JSON.toJSONString(user));
    }
}

測試結果

代表與mybatis整合成功

8 遇到的問題

mybatis綁定錯誤  

整合mybatis的過程,遇到的最大的問題,大概就是這個使人頭疼的錯誤吧

你們參考一下這篇博客

https://blog.csdn.net/gwd1154978352/article/details/68954224

小編參照博客修改了不少次,仍是報錯,個人Mapper.xml文件已經肯定沒有錯誤了,查了下,原來是maven打包的問題

maven會把resources下的xml打包成class文件,可是上面的UserMapper.xml並無放在resources下,而是單獨的建了一個包,用來存放這個xml

也就是說,自動打包的時候,不會把這份UserMapper.xml打包到class文件裏面,因此解決方法在pom文件中,強制的把xml文件打到class文件中

<build>
  <resources>
    <!-- maven項目中src源代碼下的xml等資源文件編譯進classes文件夾,
      注意:若是沒有這個,它會自動搜索resources下是否有mapper.xml文件,
      若是沒有就會報org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.pet.mapper.PetMapper.selectByPrimaryKey-->
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
    <!--將resources目錄下的配置文件編譯進classes文件  -->
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
</build>

問題解決

 

找不到JDBC鏈接

我遇到這個問題,是由於下載了最新版本的mysql,去官網找了低版本的mysql,測試成功

 

參考:https://blog.csdn.net/zhshulin/article/details/37956105

相關文章
相關標籤/搜索