mybatis模板

因为这里是说mybatis的,所以呢 servlet就不做多说了,代码也不在这里贴出来了.

log4j.properties

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.org.apache=INFO

mybatis-config.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>
<!-- 注意:一定要加在<properties>之后且<typeAliases>之前 -->
     <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
<environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/micro_message" /> <property name="username" value="root" /> <property name="password" value="gys" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/imooc/config/sqlxml/message.xml" /> </mappers> </configuration>

message.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="message">
    <resultMap type="com.imooc.bean.Message" id="MessageResult">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="COMMAND" jdbcType="VARCHAR" property="command" />
        <result column="DESCRIPTION" jdbcType="VARCHAR" property="description" />
        <result column="CONTENT" jdbcType="VARCHAR" property="content" />
    </resultMap>

    <select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
        select ID,COMMAND,DESCRIPTION,CONTENT from message 
        <where>
            <!--以下条件 test="command != null && "".equals(command.trim()) " -->
            <!-- <if test="command !=null &amp;&amp !&quot;&quot;.equals(command.trim())"> 
                and COMMAND =#{command}
            </if>  -->
            <if test="command != null and !&quot;&quot;.equals(command.trim())">
                and command=#{command}
            </if> 
            <if test="description != null and !&quot;&quot;.equals(description.trim())">
                and description like '%' #{description} '%'
            </if> 
        </where>
    </select>
    <!-- 单个删除 ,这种情况 参数用_parameter -->
    <delete id="deleteOne" parameterType="int">
        delete from message where ID=#{_parameter}
    </delete>
    
    <!-- 批量删除 -->
    <delete id="deleteBatch" parameterType="java.util.List">
        delete from message where ID in (
            <foreach collection="list" item="item" separator=",">
                #{item}
            </foreach>
        )
    </delete>
    
    <!-- 这里的keyProperty对应的是类中的属性,不是数据库中的字段,插入数据返回id主键值 -->
    <insert id="insertData" parameterType="com.imooc.bean.Message" useGeneratedKeys="true" keyProperty="id">
        insert into message
        (COMMAND,DESCRIPTION,CONTENT)
        values
        (#{command},#{description},#{content})
    </insert>
    
    <select id="getDataByCommand" parameterType="String" resultMap="MessageResult" resultType="com.imooc.bean.Message">
        select ID,COMMAND,DESCRIPTION,CONTENT from message where COMMAND=#{_parameter} limit 1
    </select>
    
</mapper>

DBAccess.java

package com.imooc.db;

import java.io.IOException;
import java.io.Reader;

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

/**
 * 访问数据库
 * @author gys
 *
 */
public class DBAccess {
    public SqlSession getSqlSession() throws IOException{
        //通过配置文件获取数据库连接信息
        Reader reader= Resources.getResourceAsReader("com/imooc/config/mybatis-config.xml");
        //通过配置信息构建一个SqlSessionFactory
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        //通过sqlSessionFactory打开一个数据库回话
        SqlSession sqlSession=sqlSessionFactory.openSession();
        return sqlSession;
    }
}

MessageDao.java

package com.imooc.dao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

/**
 * 和message表相关的数据库操作
 * @author gys
 *
 */
public class MessageDao {
    public List<Message> queryMessageList(String command,String description){
        List<Message> messageList=new ArrayList<Message>();
        DBAccess dbAccess=new DBAccess();
        SqlSession sqlSession=null;
        try {
            sqlSession= dbAccess.getSqlSession();
            Message message=new Message();
            message.setCommand(command);
            message.setDescription(description);
            
            
            //通过sqlSession执行sql语句
            messageList=sqlSession.selectList("message.queryMessageList",message);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
        return messageList;
    }
    /**
     * 单条删除
     * @param id
     */
    public void deleteOne(int id){
        DBAccess dbAccess=new DBAccess();
        SqlSession sqlSession=null;
        try {
            sqlSession= dbAccess.getSqlSession();
            //通过sqlSession执行sql语句
            int count=sqlSession.delete("message.deleteOne",id);
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
    }
    
    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids){
        DBAccess dbAccess=new DBAccess();
        SqlSession sqlSession=null;
        try {
            sqlSession= dbAccess.getSqlSession();
            //通过sqlSession执行sql语句
            int count=sqlSession.delete("message.deleteBatch",ids);
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
    }
    

    /**
     * 插入数据,获取主键
     */
    public int insertData(Message message){
        DBAccess dbAccess=new DBAccess();
        SqlSession sqlSession=null;
        int id=0;
        try {
            sqlSession= dbAccess.getSqlSession();
            //通过sqlSession执行sql语句
            int count=sqlSession.insert("message.insertData",message);//返回受影响的行数
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
        id=message.getId();
        return id;//返回插入数据的id
    }
    
    /**
     * 获取单个数据
     */
    public Message getDataByCommand(String command){
        DBAccess dbAccess=new DBAccess();
        SqlSession sqlSession=null;
        Message message=null;
        try {
            sqlSession= dbAccess.getSqlSession();
            //通过sqlSession执行sql语句
            message=sqlSession.selectOne("message.getDataByCommand",command);//返回受影响的行数
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
        return message;//返回插入数据的id
    }
    
    
}

MessageService.java

package com.imooc.service;

import java.util.ArrayList;
import java.util.List;

import com.imooc.bean.Message;
import com.imooc.dao.MessageDao;

public class MessageService {
    public List<Message> queryMessageList(String command,String description){
        MessageDao messageDao=new MessageDao();
        return messageDao.queryMessageList(command, description);
    }
    
    //单条删除
    public void deleteOne(String id){
        if(id!=null && !"".equals(id.trim())){
            MessageDao messageDao=new MessageDao();
            messageDao.deleteOne(Integer.valueOf(id));
        }
    }
    
    /**
     * 批量删除
     */
    public void deleteBatch(String[] ids){
        MessageDao messageDao=new MessageDao();
        List<Integer> list=new ArrayList<Integer>();
        if(ids==null){
            System.out.println("请选择删除的项目!");
        }else{
            for(String id:ids){
                list.add(Integer.valueOf(id));
            }        
            messageDao.deleteBatch(list);
        }
        
    }
    /**
     * 批量删除
     */
    public int insertData(Message message){
        MessageDao messageDao=new MessageDao();
        int id=messageDao.insertData(message);
        return id;
    }
    
    /**
     * 获取单个数据
     */
    public Message getDataByCommand(String command){
        MessageDao messageDao=new MessageDao();
        return messageDao.getDataByCommand(command);
    }
    
}

这些就是mybatis最基础的模板代码.供以后查找用

posted @ 2015-11-11 15:03  思思博士  阅读(477)  评论(0编辑  收藏  举报