MyBatis进阶(六)使用MyBatis改造SMS

前言

      阅读我博客的朋友们都知道,我一直拿SMS(学生管理系统)为例做讲解。在之前的讲解中,我已经使用了JSP+Servlet+DAO的实现方式完整的实现了简单的操作,代码地址:SMS。本章将对DAO层进行改造,换装我们新学的Mybatis框架,当然,还有我们的maven!

方法

1.首先大家将我们的工程改造为Maven工程,如果不清楚的话参照前面的章节:Maven入门(二)Maven工程的创建

建造好的工程目录类似于这个:

main-java:存放项目的java文件

main-resources:存放项目的资源文件,如xml

webapp:存放项目的页面文件

test-java:测试类存放处

test-resources:测试类资源文件存放处

使用Maven将用到的包引入!!

2.配置mybatis-config.xml

我的配置文件长这样(仅供参考,当然随便复制qwq):

<?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">
<!-- mybatis配置文件根路径 -->
<configuration>
    <!-- 加载数据库连接资源文件 -->
    <properties resource="db.properties"/>
    <!--<properties>
        <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="scott"/>
        <property name="password" value="tiger"/>
    </properties>-->
    <!-- 声明使用的配置信息 -->
    <settings>
        <!-- 指定所用日志的具体实现,未指定时将自动查找 -->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!-- 定义实体类的别名供用得到的地方使用 -->
    <typeAliases>
        <!-- 1.单一的为每一个类起别名 -->
        <!--<typeAlias type="cn.edu.ccut.bo.User" alias="User"></typeAlias>-->
        <!-- 2.扫描指定的包,包下所有的类自动起别名 -->
        <package name="cn.edu.ccut.bo"/>
        <package name="cn.edu.ccut.pojo"/>
    </typeAliases>
    <!-- 数据库连接环境标签,可以配置多个数据库连接,default表示默认的连接,对应每个环境的id值 -->
    <environments default="development">
        <!-- 数据库连接环境配置标签,id唯一标识每个环境 -->
        <environment id="development">
            <!-- 声明使用的事务管理方式,这里采用原生的JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源,采用数据库连接池技术 -->
            <dataSource type="POOLED">
                <!-- 定义数据库连接必备的属性 -->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置mapper文件关联 -->
    <mappers>
        <!--<mapper resource="cn/edu/ccut/mapper/StudentMapper.xml"/>-->
        <package name="cn.edu.ccut.mapper"/>
    </mappers>
</configuration>

3.配置sqlSession获取工具类

package cn.edu.ccut.dbc;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 数据库连接类
 * @author jwang
 *
 */
public class DatabaseConnection {

	private SqlSessionFactory sqlSessionFactory;
	private SqlSession sqlSession;

	//初始化连接
	public DatabaseConnection() {
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	//获取连接
	public SqlSession getConnection() {
		this.sqlSession = this.sqlSessionFactory.openSession(true);
		return this.sqlSession;
	}

	//关闭连接
	public void close(){
		if(this.sqlSession != null){
			try {
				this.sqlSession.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

4.删除原来的DAO包所有文件,新建Mapper包,并建立StudentMapper.java

福利:基本的增删改查等操作都在这里了,使用的是纯注解的开发模式,如果需要XML配置请读者自行编写

package cn.edu.ccut.mapper;

import cn.edu.ccut.bo.Student;
import cn.edu.ccut.bo.User;
import cn.edu.ccut.util.StudentSqlProvider;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Set;


public interface StudentMapper {

    @Insert("insert into student values (#{id},#{name},#{sex},#{age},#{tel},#{loc})")
    public void doCreate(Student student) throws Exception;

    @Select("select * from student where id = #{id}")
    public Student findById(@Param("id") String id) throws Exception;

    @Select("select * from student")
    public List<Student> doListAll() throws Exception;

    @Select({"select * from users where username=#{username} and password=#{password}"})
    public User doLogin(@Param("username") String username, @Param("password") String password) throws Exception;

    @SelectProvider(type = StudentSqlProvider.class,method = "doListAllForPageSql")
    public List<Student> doListAllForPage(@Param("currentPage") Integer currentPage, @Param("lineSize") Integer lineSize) throws Exception;

    @Delete("delete from student where id=#{id}")
    public void doRemove(@Param("id") String id) throws Exception;

    @Update("update student set id=#{id},name=#{name},set=#{sex},age=#{age},tel=#{tel},loc=#{loc} where id=#{id}")
    public void doUpdate(Student student) throws Exception;

    @DeleteProvider(type = StudentSqlProvider.class,method = "doDeleteAll")
    public void doBantchRemove(Set<String> all) throws Exception;

}

到这里,MyBatis的替代性改造基本上就结束了!我们知道它主要是简化了我们DAO层次的开发,service当然还是沿用原来的写法!

项目的全部代码我会进行上传,大家尽情参阅,互相学习!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值