MyBatis-Spring整合操作对数据库进行增删改查

MyBatis-Spring整合操作对数据库进行增删改查


欢迎探讨,点击>此处<,mybatis配置可查看上篇demo


整体项目结构如下

MyBatis-Spring整合操作对数据库进行增删改查_第1张图片

一、引入maven依赖

整合版本需要有一定的对应关系,在官网都是可以查询对应关系的,这里我使用的都是最新的版本依赖

<dependencies>
        <!-- 基础依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>

        <!-- spring依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>



        <!-- 数据源c3p0 -->
        <dependency>
            <!--
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            -->
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>


        <!-- mybatis-spring整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>

二、创建表

create table user(
	uid int primary key auto_increment,
	name varchar(10) not null,
	age int not null
) charset utf8;

三、编辑spring、mybatis配置文件以及mybatis的用户bean映射xml,用户bean将在下一步贴出代码

mybatis-conf.xml

<?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>
    <typeAliases>
        <typeAlias type="top.it1002.mybatisspring.domain.User" alias="_user"/>
    </typeAliases>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

beans.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"
       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-4.3.xsd
        ">
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
        <property name="maxPoolSize" value="10"/>
        <property name="minPoolSize" value="2"/>
        <property name="initialPoolSize" value="3"/>
    </bean>

    <!-- 配置mybatis -->
    <bean name="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="mybatis-conf.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <context:component-scan base-package="top.it1002.mybatisspring.domain,top.it1002.mybatisspring.dao,top.it1002.mybatisspring.service.impl"/>


</beans>

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="user">
    <!---->
    <select id="select" parameterType="int" resultType="_user">
      select * from user where uid = #{uid}
    </select>

    <select id="selectAll" resultType="_user">
        select * from user
    </select>

    <!---->
    <update id="update" parameterType="_user">
        update user
        <set>
            <if test="age != null">age = #{age},</if>
            <if test="name != null">name = #{name}</if>
        </set>
        where uid = #{uid}
    </update>

    <!---->
    <insert id="insert">
        insert user(name, age) values(#{name}, #{age})
    </insert>

    <!---->
    <delete id="delete" parameterType="int">
        delete from user where uid = #{uid}
    </delete>

    <delete id="deleteAll">
        delete from user;
    </delete>

</mapper>

四、准备代码

BaseDao.java

package top.it1002.mybatisspring.dao;

import java.util.List;

public interface BaseDao<T> {
    public void insert(T t);

    public void delete(int id);

    public T select(int id);

    public List<T> selectAll();

    public void update(T t);

}

UserDao.java

package top.it1002.mybatisspring.dao;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import top.it1002.mybatisspring.domain.User;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author      王磊
 * @Date        2019/3/15
 * @ClassName   UserDao
 * @Description 用户数据库操作层
 **/
@Repository(value = "userDao")
public class UserDao extends SqlSessionDaoSupport implements BaseDao<User> {

    @Resource(name = "sqlSessionFactoryBean")
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    public void insert(User user) {
        getSqlSession().insert("user.insert", user);
    }

    public void delete(int id) {
        getSqlSession().delete("user.delete", id);
    }

    public User select(int id) {
        return getSqlSession().selectOne("user.select", id);
    }

    public List<User> selectAll() {
        return getSqlSession().selectList("user.selectAll");
    }

    public void update(User user) {
        getSqlSession().update("user.update", user);
    }
}

User.java

package top.it1002.mybatisspring.domain;

import org.springframework.stereotype.Repository;

/**
 * @Author      王磊
 * @Date        2019/3/15
 * @ClassName   User
 * @Description 用户bean
 **/
@Repository
public class User {
    private String name;
    private int age;
    private int uid;

    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 getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }
}

BaseService.java

package top.it1002.mybatisspring.service;

import java.util.List;

public interface BaseService<T> {
    public void insert(T t);

    public void delete(int id);

    public void update(T t);

    public T select(int id);

    public List<T> selectAll();
}

UserService.java

package top.it1002.mybatisspring.service;

import top.it1002.mybatisspring.domain.User;

/**
 * 用户业务层面扩展类
 */
public interface UserService extends BaseService<User> {
    Object userOtherDo();
}

UserServiceImpl .java

package top.it1002.mybatisspring.service.impl;

import org.springframework.stereotype.Service;
import top.it1002.mybatisspring.dao.UserDao;
import top.it1002.mybatisspring.domain.User;
import top.it1002.mybatisspring.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author      王磊
 * @Date        2019/3/15
 * @ClassName   UserServiceImpl
 * @Description 用户业务层实现类
 **/
@Service
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Resource(name = "userDao")
    public void setUserDao(UserDao userDao){
        this.userDao = userDao;
    }

    public void insert(User user) {
        userDao.insert(user);
    }

    public void delete(int id) {
        userDao.delete(id);
    }

    public void update(User user) {
        userDao.update(user);
    }

    public User select(int id) {
        return userDao.select(id);
    }

    public List<User> selectAll() {
        return userDao.selectAll();
    }

    public Object userOtherDo() {
        // ....................
        return null;
    }
}

MyBatisSpringUtil .java

package top.it1002.mybatisspring.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.it1002.mybatisspring.domain.User;

/**
 * @Author      王磊
 * @Date        2019/3/16
 * @ClassName   MyBatisSpringUtil
 * @Description 工具类
 **/
public class MyBatisSpringUtil {

    /**
     * 获取bean容器应用上下文对象
     * @return
     */
    public static ApplicationContext getApplicationContext(){
        return new ClassPathXmlApplicationContext("beans.xml");
    }

    public static void userInfoConsole(User user){
        if(user != null){
            System.out.println("=== 用户:" + user.getName() + "信息如下 ===");
            System.out.println("用户id:" + user.getUid());
            System.out.println("用户名:" + user.getName());
            System.out.println("用户年龄:" + user.getAge());
        }else{
            System.out.println("用户信息异常!");
        }
    }
}

五、结束测试调用

App.java

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.it1002.mybatisspring.domain.User;
import top.it1002.mybatisspring.service.UserService;
import top.it1002.mybatisspring.service.impl.UserServiceImpl;
import top.it1002.mybatisspring.util.MyBatisSpringUtil;

import java.util.List;


/**
 * @Author      王磊
 * @Date        2019/3/15
 * @ClassName   App
 * @Description 调用类
 **/
public class App {
    public static void main(String[] args) throws Exception {
        ApplicationContext ac = MyBatisSpringUtil.getApplicationContext();
        UserServiceImpl userService = (UserServiceImpl)ac.getBean("userServiceImpl");
        // 测试c3p0连接
        /*/
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        ComboPooledDataSource dataSource = (ComboPooledDataSource)ac.getBean("dataSource");
        System.out.println(dataSource.getConnection());
        //*/

        // 插入数据测试
        /*/
        User user = (User) ac.getBean("user");
        user.setAge(22);
        user.setName("admin");
        userService.insert(user);
        //*/

        // 查询数据测试1
        /*/
        int uid = 1;
        User user1 = userService.select(uid);
        MyBatisSpringUtil.userInfoConsole(user1);
        //*/

        // 查询数据测试2
        /*/
        List userList = userService.selectAll();
        for(User user2 : userList){
            MyBatisSpringUtil.userInfoConsole(user2);
        }
        //*/

        // 修改数据测试
        /*/
        User user3 = (User) ac.getBean("user");
        user3.setUid(1);
        user3.setName("admin");
        user3.setAge(18);
        userService.update(user3);
        //*/

        // 删除数据测试
        /*/
        int uid = 1;
        userService.delete(uid);
        //*/
    }
}

你可能感兴趣的:(Java,SSM)