Spring+Mybatis整合

首先创建数据库mybatis并创建表customer

工程可以选择创建SpringBoot工程也可以创建maven web工作

创建maven Web工程需要导入一下依赖

        <!--springwebmvc可以导入spring全部核心依赖-->        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--dbcp连接池-->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

如果选择创建SpringBoot工程需导入以下依赖

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--dbcp连接池-->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

导入依赖后在resources下创建database.properties添加数据库连接池配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=root
jdbc.minIdle=45
jdbc.maxIdle=50
jdbc.initialSize=5
jdbc.maxActive=100
jdbc.maxWait=100
jdbc.removeAbandonedTimeout=180
jdbc.removeAbandoned=true

在resources下创建spring-mybatis.xml(名字可以随意写)添加数据库连接池并配置spring扫描包、配置sqlsession工厂和mapper动态代理

<?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">
    
    <context:component-scan base-package="com.wang.hxci.*"/>
    <context:property-placeholder location="classpath:database.properties"/>
    <bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" scope="singleton">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
    </bean>

    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--<property name="configLocation" value="classpath:mybatis-config.xml"/>-->
        <property name="typeAliasesPackage" value="com.wang.hxci.pojo" ></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    <!--扫描映射文件(mapper动态代理)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"  value="com.wang.hxci.dao"/>
    </bean>

</beans>

创建Customer实体类添加get/set,toString方法

package com.wang.hxci.pojo;

public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;

    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;
    }

    public String getJobs() {
        return jobs;
    }

    public void setJobs(String jobs) {
        this.jobs = jobs;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

创建dao层

package com.wang.hxci.dao;

import com.wang.hxci.pojo.Customer;

import java.util.List;

public interface CustomerDao {
    public List<Customer> query();

    public void add(Customer customer);
}

在resources下创建mapper文件夹并在mapper下创建customerMapper.xml(注意:namespace的接口和方法的返回值类型)

<?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.wang.hxci.dao.CustomerDao">
    <select id="query" resultType="com.wang.hxci.pojo.Customer">
       select * from customer
    </select>
    <insert id="add">
        insert  into customer(username,jobs,phone) values (#{username},#{jobs},#{phone})
    </insert>
</mapper>

创建service层(业务层)(业务层与dao层代码相同)

package com.wang.hxci.service;

import com.wang.hxci.pojo.Customer;

import java.util.List;

public interface CustomerService {
    public List<Customer> query();

    public void add(Customer customer);
}

创建serviceimpl(业务层的接口实现类)(注意:@Service是将实现类添加到spring组件中)

package com.wang.hxci.service.impl;

import com.wang.hxci.dao.CustomerDao;
import com.wang.hxci.pojo.Customer;
import com.wang.hxci.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    CustomerDao dao ;

    public List<Customer> query() {
        List<Customer> list = dao.query();
        return list;
    }

    public void add(Customer customer) {
        dao.add(customer);
    }
}

创建controller层实现调用

package com.wang.hxci.controller;

import com.wang.hxci.pojo.Customer;
import com.wang.hxci.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
public class CustomerController {
    @Autowired
    CustomerService service;

    public String query(){
        List<Customer> list = service.query();
        System.out.println(list);
        return null;
    }

    public String add(Customer customer){
        service.add(customer);
        return null;
    }

}

最后创建测试类测试(getBean("customerController是由controller层中的@Controller进行装配"))

package com.wang;

import com.wang.hxci.controller.CustomerController;
import com.wang.hxci.pojo.Customer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");
        CustomerController controller = (CustomerController)context.getBean("customerController");
        Customer customer =new Customer();
        customer.setUsername("张三");
        customer.setPhone("12222222");
        customer.setJobs("java");
        controller.add(customer);
        controller.query();
    }
}

运行结果

 

手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis 博客地址:http://blog.csdn.net/qq598535550/article/details/51703190 我们看招聘信息的时候,经常会看到这一点,需要具备SSH框架的技能;而且在大部分教学课堂中,也会把SSH作为最核心的教学内容。 但是,我们在实际应用中发现,SpringMVC可以完全替代Struts,配合注解的方式,编程非常快捷,而且通过restful风格定义url,让地址看起来非常优雅。 另外,MyBatis也可以替换Hibernate,正因为MyBatis的半自动特点,我们程序猿可以完全掌控SQL,这会让有数据库经验的程序猿能开发出高效率的SQL语句,而且XML配置管理起来也非常方便。 好了,如果你也认同我的看法,那么下面我们一起来做整合吧! 在写代码之前我们先了解一下这三个框架分别是干什么的? 相信大以前也看过不少这些概念,我这就用大白话来讲,如果之前有了解过可以跳过这一大段,直接看代码! SpringMVC:它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login ,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只返回json/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!! Spring:太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。 MyBatis:如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦捂脸)编写的代码能搞提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AqrJan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值