美文网首页
Intellij 中 集成SpringMVC MyBatis

Intellij 中 集成SpringMVC MyBatis

作者: androidtiger | 来源:发表于2018-11-30 14:53 被阅读0次

    Intellij 中集成SrpingMvc MyBatis。Web开发中,java跟众多的Web开发语言一样也拥有很多web开发框架,以此让程序员提高开发效率,在javaEE中用的最多的恐怕就是Spring框架了。虽然对老司机来说,开发环境的搭建可谓轻车熟路,但是对新手来说,难免会遇到很多坑。好了废话多说无益,这里直接上步骤。

    1.准备工作

    1.1 安装javaSDK,请自行选择安装版本,目前一般用的多的是java7或者java8。我这里用的是java8,您可以自行选择下载安装,并配置好系统环境变量。不会安装,请自行百度哟。
    1.2 安装Tomcat ,请注意tomcat的版本与JDK版本的对应关系。Tomcat7.x以上要JDK 6.0及以上版本才能兼容,版本对照表您可以自行检索资料,同样安装好后请配置好环境变量。
    1.3 安装IDE,这里我们安装JetBrains出的Intellij.这IDE不多说,比Eclipse好用太多。IDE安装教程您可以自行检索资料,这里不提供。
    1.4 安装MySql,对就是Mysql.我安装的是mysql8.0,mysql的版本会影响Spring JDBC的配置与连接,主要是驱动不一样。后面会提到。
    1.5 安装maven,下载好maven,安装到本地磁盘,进入【conf】目录,选择setting.xml,配置本地仓库,修改默认本地仓库,localRepository,修改到C盘以外的位置。怎么配置,也请检索资料,自行解决,这个不难的。

    2.开工

    前面我们已经做好了准备工作, 该装的都已经装了,那么我们开始吧。

    2.1 新建工程
    1.新建工程
    2.创建maven项目 3.填写包名与项目名 4.修改maven配置
    5.配置本地项目文件路径,点击下一步
    6.maven项目构建成功。Build Success
    7.项目文件结构,src代码文件,pom.xml依赖配置文件
    2.2配置相关目录与文件

    2.2.1 pom.xml 添加Spring项目需要的相关依赖。这里mysql因为是8.0这里将version修改为8.0.11

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      Licensed to the Apache Software Foundation (ASF) under one
      or more contributor license agreements.  See the NOTICE file
      distributed with this work for additional information
      regarding copyright ownership.  The ASF licenses this file
      to you under the Apache License, Version 2.0 (the
      "License"); you may not use this file except in compliance
      with the License.  You may obtain a copy of the License at
    
       http://www.apache.org/licenses/LICENSE-2.0
    
      Unless required by applicable law or agreed to in writing,
      software distributed under the License is distributed on an
      "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      KIND, either express or implied.  See the License for the
      specific language governing permissions and limitations
      under the License.
    -->
    <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
    <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/maven-v4_0_0.xsd">
    
      <modelVersion>4.0.0</modelVersion>
      <packaging>war</packaging>
    
      <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
    
      <name>com.hm</name>
      <groupId>hmhealth</groupId>
      <artifactId>com.hm</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.7</version>
            <configuration>
              <connectors>
                <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                  <port>8888</port>
                  <maxIdleTime>30000</maxIdleTime>
                </connector>
              </connectors>
              <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
              <contextPath>/</contextPath>
            </configuration>
          </plugin>
        </plugins>
      </build>
    
      <dependencies>
        <!--dependency>
          <groupId>hmhealth</groupId>
          <artifactId>[the artifact id of the block to be mounted]</artifactId>
          <version>1.0-SNAPSHOT</version>
        </dependency-->
        <dependency>
          <!--3.0的junit是使用编程的方式来进行测试,而junit4是使用注解的方式来运行junit-->
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.12</version>
        </dependency>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-core</artifactId>
          <version>1.1.1</version>
        </dependency>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.1.1</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.11</version>
          <scope>runtime</scope>
        </dependency>
        <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.1</version>
        </dependency>
    
        <!--2.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>
    
        <!--3.Servlet web相关依赖-->
        <dependency>
          <groupId>taglibs</groupId>
          <artifactId>standard</artifactId>
          <version>1.1.2</version>
        </dependency>
        <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.5.4</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</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>
        <!--3)springweb相关依赖-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.1.7.RELEASE</version>
        </dependency>
        <!--4)spring test相关依赖-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>RELEASE</version>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>RELEASE</version>
        </dependency>
      </dependencies>
    </project>
    

    2.2.2 创建相关的目录与文件,目录结构如下。


    controller,dao,model,service,资源文件夹下创建mapper,spring,jdbc.properties,mybatis-config

    2.2.3相关文件code
    1.模型类User.Class

    /**
     * Created by zi198 on 2018/11/29
     */
    
    public class User {
        public int id;
        public String name;
        public int age;
        public int password;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public int getPassword() {
            return password;
        }
    
        public void setPassword(int password) {
            this.password = password;
        }
    }
    
    

    2.Dao接口

    import com.hmweb.model.User;
    
    import java.util.List;
    
    /**
     * Created by zi198 on 2018/11/29
     */
    
    public interface UserMapper {
        List<User> getAll();
    
        void save(User user);
    
        void delete(int id);
    
        void update(User user);
    
        User getUserById(int id);
    }
    

    3.UserService

    package com.hmweb.service;
    
    import com.hmweb.model.User;
    
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    /**
     * Created by zi198 on 2018/11/29
     */
    @Transactional
    public interface UserService {
        List<User> getAll();
    
        void save(User user);
    
        void delete(int id);
    
        void update(User user);
    
        User getUserById(int id);
    }
    

    4.UserService实现类

    import com.hmweb.dao.UserMapper;
    import com.hmweb.model.User;
    import com.hmweb.service.UserService;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * Created by zi198 on 2018/11/29
     */
    @Service("userService")
    public class UserServicelmpl implements UserService {
        @Autowired
        UserMapper userMapper;
        public List<User> getAll() {
            return userMapper.getAll();
        }
    
        public void save(User user) {
            userMapper.save(user);
        }
    
        public void delete(int id) {
            userMapper.delete(id);
        }
    
        public void update(User user) {
            userMapper.update(user);
        }
    
        public User getUserById(int id) {
            return userMapper.getUserById(id);
        }
    }
    
    

    5.mapper/UserMapper.xml

    <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.hmweb.dao.UserMapper">
        <!--目的:为dao接口方法提供sql语句配置
        即针对dao接口中的方法编写我们的sql语句-->
    
        <select id="getAll" resultType="com.hmweb.model.User">
            select * from t_user
        </select>
        <select id="getUserById" resultType="com.hmweb.model.User" parameterType="int">
            select * from t_user where id=#{id}
        </select>
        <insert id="save" parameterType="com.hmweb.model.User">
            insert into t_user(id,name,age,password) values(#{id},#{name},#{age},#{password})
        </insert>
        <delete id="delete" parameterType="int">
            delete from t_user where id=#{id}
        </delete>
        <update id="update" parameterType="com.hmweb.model.User">
            update t_user set name=#{name},age=#{age},password=#{password} where id=#{id}
        </update>
    </mapper>
    

    6.spring-dao

    <?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.配置数据库相关参数-->
        <context:property-placeholder location="classpath:jdbc.properties"/>
    
        <!--2.数据库连接池-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!--配置连接池属性-->
            <property name="driverClass" value="${jdbc.driver}"/>
    
            <!-- 基本属性 url、user、password -->
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    
            <!--c3p0私有属性-->
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
            <!--关闭连接后不自动commit-->
            <property name="autoCommitOnClose" value="false"/>
    
            <!--获取连接超时时间-->
            <property name="checkoutTimeout" value="10000"/>
            <!--当获取连接失败重试次数-->
            <property name="acquireRetryAttempts" value="2"/>
        </bean>
    
        <!--约定大于配置-->
        <!--3.配置SqlSessionFactory对象-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!--往下才是mybatis和spring真正整合的配置-->
            <!--注入数据库连接池-->
            <property name="dataSource" ref="dataSource"/>
            <!--配置mybatis全局配置文件:mybatis-config.xml-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <!--扫描entity包,使用别名,多个用;隔开-->
            <property name="typeAliasesPackage" value="com.hmweb"/>
            <!--扫描sql配置文件:mapper需要的xml文件-->
            <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        </bean>
    
        <!--4:配置扫描Dao接口包,动态实现DAO接口,注入到spring容器-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!--注入SqlSessionFactory-->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!-- 给出需要扫描的Dao接口-->
            <property name="basePackage" value="com.hmweb.dao"/>
        </bean>
    </beans>
    

    7.spring-service

    <?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" xmlns:tx="http://www.springframework.org/schema/tx"
           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/spring-tx.xsd">
        <!--扫描service包下所有使用注解的类型-->
        <context:component-scan base-package="com.hmweb.service"/>
        <!--配置事务管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!--注入数据库连接池-->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <bean id="date" class="java.util.Date"></bean>
        <!--配置基于注解的声明式事务
        默认使用注解来管理事务行为-->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    </beans>
    

    8.spring-web

    <?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" xmlns:tx="http://www.springframework.org/schema/tx"
           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/spring-tx.xsd">
        <!--扫描service包下所有使用注解的类型-->
        <context:component-scan base-package="com.hmweb.service"/>
        <!--配置事务管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!--注入数据库连接池-->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <bean id="date" class="java.util.Date"></bean>
        <!--配置基于注解的声明式事务
        默认使用注解来管理事务行为-->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    </beans>
    

    9.jdbc.properties

    jdbc.url: jdbc:mysql://localhost:3306/hm?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
    jdbc.driver: com.mysql.cj.jdbc.Driver
    jdbc.username=root
    jdbc.password=123456
    

    10.mybatis-config

    <?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的getGeneratekeys获取自增主键值-->
            <setting name="useGeneratedKeys" value="true"/>
            <!--使用列别名替换列名  默认值为true
            select name as title(实体中的属性名是title) form table;
            开启后mybatis会自动帮我们把表中name的值赋到对应实体的title属性中
            -->
            <setting name="useColumnLabel" value="true"/>
            <!--开启驼峰命名转换Table:create_time到 Entity(createTime)-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>
    </configuration>
    

    11.web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4"
             xmlns="http://java.sun.com/xml/ns/j2ee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
      <!--用maven创建的web-app需要修改servlet的版本为3.1-->
      <!--配置DispatcherServlet-->
      <servlet>
        <servlet-name>cjq-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
            配置SpringMVC 需要配置的文件
            spring-dao.xml,spring-service.xml,spring-web.xml
            Mybites -> spring -> springMvc
        -->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>cjq-dispatcher</servlet-name>
        <!--默认匹配所有请求-->
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
    
      <welcome-file-list>
        <welcome-file>/login.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    

    11.写测试类,

    package com.hmweb;
    
    import com.hmweb.model.User;
    import com.hmweb.service.UserService;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.util.Date;
    import java.util.List;
    
    import javax.annotation.Resource;
    
    /**
     * Created by zi198 on 2018/11/29
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations="classpath:spring/spring-*.xml")
    public class UserServiceImplTest {
        @Resource
        Date date;
        @Resource
        UserService userService;
    
        @Test
        public void testDate(){
            System.out.println(date);
        }
        @Test
        public void testGetAll(){
            List<User> list=userService.getAll();
            for(User user:list){
                System.out.println(user.getName());
            }
        }
        @Test
        public void testGetUserById(){
            System.out.println(userService.getUserById(1).getName());
        }
        @Test
        public void testSave(){
            User user=new User();
            user.setName("test");
            user.setAge(11);
            user.setPassword(111222);
            userService.save(user);
        }
        @Test
        public void testDelete(){
            userService.delete(1);
        }
        @Test
        public void testUpdate(){
            User user=userService.getUserById(2);
            user.setName("hello");
            userService.update(user);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Intellij 中 集成SpringMVC MyBatis

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