使用Eclipse,Maven简单搭建Spring+MyBatis

时间:2022-04-02 05:13:04

 

1、新建一个Maven Project

使用Eclipse自带的Maven插件,自动创建一个基于Maven的Web工程;(前提是开发环境一定要配置好Maven)

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

 

选择archetype为maven-archetype-webapp:

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

设置:

       GroupId:com.study(正式项目为公司网址倒写)

       ArtifactId:SMPro(项目名称,[模块名称])

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

2、修复jsp页面报错

jsp页面报错,因为在构建路径中没有javax.servlet.http.HttpServlet,在pom.xml文件中添加servlet依赖包:

<dependency>

       <groupId>javax.servlet</groupId>

       <artifactId>javax.servlet-api</artifactId>

       <version>3.1.0</version>

       <!-- 只在编译和测试时运行 -->

       <scope>provided</scope>

</dependency>

3、完善项目目录结构

在Navigator视图下,补全目录结构如下:

使用Eclipse,Maven简单搭建Spring+MyBatis

 

 

右键项目-Properties,打开Java Build Path,补全Source下的目录,并观察Default output folder是否为***/target/classes目录;

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

4、添加该测试项目所需依赖jar包:

<dependencies>

       <!-- 使用junit4 -->

       <dependency>

              <groupId>junit</groupId>

              <artifactId>junit</artifactId>

              <version>4.11</version>

              <scope>test</scope>

       </dependency>

       <dependency>

              <groupId>javax.servlet</groupId>

              <artifactId>javax.servlet-api</artifactId>

              <version>3.1.0</version>

              <!-- 只在编译和测试时运行 -->

              <scope>provided</scope>

       </dependency>

      

       <!-- 补全项目依赖 -->

       <!-- 1:日志

           slf4j是规范/接口

         日志实现:log4j,logback,common-logging

         这里使用:slf4j + log4j

       -->

       <dependency>

              <groupId>org.slf4j</groupId>

              <artifactId>slf4j-log4j12</artifactId>

              <version>1.7.2</version>

       </dependency>

       <!-- 2:数据库相关依赖 -->

        <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-java</artifactId>

           <version>5.1.39</version>

           <scope>runtime</scope>

       </dependency>

       <!-- c3p0数据库连接池 -->

       <dependency>

           <groupId>c3p0</groupId>

           <artifactId>c3p0</artifactId>

           <version>0.9.1.2</version>

       </dependency>

        <!-- 3:DAO框架依赖:MyBatis依赖 -->

       <dependency>

           <groupId>org.mybatis</groupId>

           <artifactId>mybatis</artifactId>

           <version>3.3.0</version>

       </dependency>

       <!-- MyBatis自身实现的spring整合依赖 -->

       <dependency>

           <groupId>org.mybatis</groupId>

           <artifactId>mybatis-spring</artifactId>

           <version>1.2.3</version>

       </dependency>

       <!-- 4:spring依赖 -->

       <!-- 1) spring核心依赖-->

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-core</artifactId>

           <version>4.1.7.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-beans</artifactId>

           <version>4.1.7.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-context</artifactId>

           <version>4.1.7.RELEASE</version>

       </dependency>

       <!-- 2) spring dao层依赖-->

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-jdbc</artifactId>

           <version>4.1.7.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-tx</artifactId>

           <version>4.1.7.RELEASE</version>

       </dependency>

</dependencies>

5、建库建表

--创建数据库

CREATE DATABASE sm_project;

USE sm_project;

--创建用户表

CREATE TABLE tb_user(

       `user_id`                            INT PRIMARY KEY AUTO_INCREMENT COMMENT '用户ID',

       `user_name`       VARCHAR(30) COMMENT '用户名',

       `user_birthday`   DATE COMMENT '用户生日',

       `user_salary`              DOUBLE COMMENT '用户工资'

)ENGINE=InnoDB DEFAULT CHARSET=UTF8 COMMENT='用户表';

6、创建实体类

使用Eclipse,Maven简单搭建Spring+MyBatis

 

 

@SuppressWarnings("serial")

public class User implements Serializable {

       private int id;

       private String name;

       private Date birthday;

       private double salary;

    //setter()/getter()/toString()略

}

7、定义DAO接口

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

public interface IUserDAO {

       public void insert(User user);

       public void delete(int id);

       public void update(User user);

       public User findById(int id);

       public List<User> findAll();

}

8、MyBatis中SQL映射文件:IUserDAO.xml

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

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

<!-- 其中命名空间指向与该文件同名的DAO层接口 -->

<mapper namespace="com.study.dao.IUserDAO">

       <!-- 通过resultMap解决实体类属性与数据库字段名不一致的问题 -->

       <resultMap type="com.study.entity.User" id="userResult">

              <!--

                     其中id为主键,result为普通字段

                     property对应实体类属性,column对应字段名(更准确的说应该是查询结果集中的字段名)

              -->

              <id property="id" column="user_id"/>

              <result property="name" column="user_name"/>

              <result property="birthday" column="user_birthday"/>

              <result property="salary" column="user_salary"/>

       </resultMap>

       <!-- 插入数据后获得自增主键的值 -->

       <insert id="insert" keyProperty="id" keyColumn="user_id">

              INSERT INTO tb_user

                     (user_name,user_birthday,user_salary)

              VALUES

                     (#{name},#{birthday},#{salary})

       </insert>

       <!-- 修改用户内容 -->

       <update id="update">

              UPDATE tb_user

              SET

                     user_name=#{name},

                     user_birthday=#{birthday},

                     user_salary=#{salary}

              WHERE

                     user_id=#{id}

       </update>

       <!-- 根据id删除用户 -->

       <delete id="delete">

              DELETE FROM tb_user WHERE user_id=#{id}

       </delete>

       <!-- 根据id查询用户 -->

       <select id="findById" resultMap="userResult">

              SELECT user_id,user_name,user_birthday,user_salary FROM tb_user WHERE user_id=#{id}

       </select>

       <!-- 查询所有用户 -->

       <select id="findAll" resultMap="userResult">

              SELECT user_id,user_name,user_birthday,user_salary FROM tb_user

       </select>

</mapper>

9、MyBatis的配置文件:mybatis-config.xml

虽然后面使用Spring托管MyBatis,但是对于MyBatis的专属设置还是需要在这里设置;

 使用Eclipse,Maven简单搭建Spring+MyBatis

 

<?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>

        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->

        <setting name="useGeneratedKeys" value="true"/>

        <!-- 使用列别名替换列名 默认:true -->

        <setting name="useColumnLabel" value="true"/>

        <!-- 开启驼峰命名转换 -->

        <setting name="mapUnderscoreToCamelCase" value="true"/>

    </settings>

</configuration>

10、Spring与MyBatis整合配置文件:spring-mybatis.xml

 使用Eclipse,Maven简单搭建Spring+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: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">

       <!-- 配置整合MyBatis -->

       <!-- 1:配置数据库相关参数 properties属性:${url} -->

       <context:property-placeholder location="classpath:jdbc.properties" />

       <!-- 2:数据库连接池 -->

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

              <!-- 关闭连接后不自动commit -->

              <property name="autoCommitOnClose" value="${autoCommitOnClose}" />

              <!-- 获取连接超时时间 -->

              <property name="checkoutTimeout" value="${checkoutTimeout}" />

              <!-- 当获取连接失败重试次数 -->

              <property name="acquireRetryAttempts" value="${acquireRetryAttempts}" />

       </bean>

      

       <!-- spring + MyBatis 精华 -->

    <!-- 约定大于配置 -->

    <!-- 3:配置SqlSessionFactory对象 -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <!-- 注入数据库连接池 -->

        <property name="dataSource" ref="dataSource"/>

        <!-- 配置MyBatis全局配置文件:mybatis-config.xml -->

        <property name="configLocation" value="classpath:mybatis-config.xml"/>

        <!-- 扫描entity包 使用别名 org.asset.entity.User -> User -->

        <property name="typeAliasesPackage" value="com.study.entity"/>

        <!-- 扫描sql配置文件:mapper需要的xml文件 -->

        <property name="mapperLocations" value="classpath:mapper/*.xml"/>

    </bean>

 

    <!-- 4:配置扫描DAO接口包,动态实现DAO接口,并注入到spring容器中 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <!-- 给出需要扫描DAO接口包 -->

        <property name="basePackage" value="com.study.dao"/>

        <!-- 注入sqlSessionFactory -->

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

    </bean>

 

</beans>

11、数据库连接配置文件:jdbc.properties

使用Eclipse,Maven简单搭建Spring+MyBatis

 

 

#jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/sm_project?useUnicode=true&characterEncoding=utf-8

jdbc.username=root

jdbc.password=

 

maxPoolSize=30

minPoolSize=10

autoCommitOnClose=false

checkoutTimeout=1000

acquireRetryAttempts=2

12、日志配置文件:log4j.properties

使用Eclipse,Maven简单搭建Spring+MyBatis

 

 

log4j.rootLogger=DEBUG, 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

13、测试

使用Eclipse,Maven简单搭建Spring+MyBatis

 

使用Eclipse,Maven简单搭建Spring+MyBatis

 

 

package com.study.dao;

import java.util.Date;

import java.util.List;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.study.entity.User;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration({"classpath:spring-mybatis.xml"})

public class IUserDAOTest {

       private Logger logger = LoggerFactory.getLogger(IUserDAOTest.class);

       @Autowired

       private IUserDAO userDAO;

       @Test

       public void testInsert() {

              User user = new User();

              user.setBirthday(new Date());

              user.setName("James");

              user.setSalary(15000.0);

              this.userDAO.insert(user);

              logger.info("insert the user={}",user);

              this.userDAO.delete(user.getId());

              User u = this.userDAO.findById(user.getId());

              logger.info("after delete the user={}", u);

       }

       @Test

       public void testUpdate() {

              User user = new User();

              user.setBirthday(new Date());

              user.setName("Daniel");

              user.setSalary(13000.0);

              logger.info("before update the user={}", user);

              this.userDAO.insert(user);

              user.setSalary(22000.0);

              this.userDAO.update(user);

              User u = this.userDAO.findById(user.getId());

              logger.info("after update the user={}", u);

              this.userDAO.delete(u.getId());

       }

       @Test

       public void testFindAll() {

              List<User> users = this.userDAO.findAll();

              logger.info("all the users={}", users);

       }

}

打印日志结果如下:

2017-08-24 15:21:06,805 [main] INFO  [com.study.dao.IUserDAOTest] - all the users=[User [id=1, name=John, birthday=Wed Aug 23 00:00:00 CST 2017, salary=10000.0], User [id=2, name=Smith, birthday=Thu Aug 24 00:00:00 CST 2017, salary=20000.0], User [id=4, name=King, birthday=Thu Aug 24 00:00:00 CST 2017, salary=30000.0]]

2017-08-24 15:21:06,818 [main] INFO  [com.study.dao.IUserDAOTest] - insert the user=User [id=11, name=James, birthday=Thu Aug 24 15:21:06 CST 2017, salary=15000.0]

2017-08-24 15:21:06,825 [main] INFO  [com.study.dao.IUserDAOTest] - after delete the user=null

2017-08-24 15:21:06,834 [main] INFO  [com.study.dao.IUserDAOTest] - before update the user=User [id=12, name=Daniel, birthday=Thu Aug 24 00:00:00 CST 2017, salary=13000.0] 2017-08-24 15:21:06,840 [main] INFO  [com.study.dao.IUserDAOTest] - after update the user=User [id=12, name=Daniel, birthday=Thu Aug 24 00:00:00 CST 2017, salary=22000.0]