程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> MyBatis的經典案例,MyBatis經典案例

MyBatis的經典案例,MyBatis經典案例

日期:2017/1/18 11:50:44      編輯:JAVA綜合教程

MyBatis的經典案例,MyBatis經典案例


    1.首先我們先了解Mybatis的一些jar包

    ---和項目框架

     

    2.接下來就看看mybatis的配置文件(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>
     <!-- 別名 -->
     <typeAliases >
     <package name="cn.happy.entity"/>
     </typeAliases>
     
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc的事務 -->
            <transactionManager type="JDBC" />
            <!-- 使用自帶的連接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
                <property name="username" value="happy" />
                <property name="password" value="1" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!-- 連接小配置 --> <mapper resource="cn/happy/dao/StudentDAO.xml" /> </mappers> </configuration>

 

    3.在dao層的小配置(StudentDAO.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="cn.happy.dao">

    <!-- 添加 -->
    <insert id="insertStudent">
        insert into student(stuno,stuname,stuage,studate)
        values(ssm.nextval,#{stuname},#{stuage},#{studate})

        <selectKey keyProperty="stuno" resultType="int">
            select SSM.CURRVAL from dual
        </selectKey>
    </insert>
    <!-- 查詢所有 -->
    <select id="findAll" resultType="Student">
        select * from student
    </select>

    <!-- 模糊查詢 -->
    <select id="findAllLike" resultType="Student">
        <!-- 不管參數為什麼都可以 -->
         <!--select * from student where stuname like concat('%',#{stuname},'%')--> 
          <!-- 字符串 -->
         <!--  select * from student where  stuname like '%${value}%' -->
         <!-- 對象 -->
         select * from student where  stuname like '%${stuname}%'
    </select>

    <!--刪除學生 -->

    <delete id="delStudent">
        delete from student where stuno=#{id}<!-- #{id}隨便寫,起到一個占位的作用 -->
    </delete>

</mapper>

 

 

     4.entity層實體類(Student)

 

package cn.happy.entity;

import java.util.Date;

public class Student {

    private int stuno;
    private String stuname;
    private int stuage;
    private Date studate;
    public String toString() {
        return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
                + stuage + ", studate=" + studate + "]";
    }
    public int getStuno() {
        return stuno;
    }
    public void setStuno(int stuno) {
        this.stuno = stuno;
    }
    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }
    public int getStuage() {
        return stuage;
    }
    public void setStuage(int stuage) {
        this.stuage = stuage;
    }
    public Date getStudate() {
        return studate;
    }
    public void setStudate(Date studate) {
        this.studate = studate;
    }
    
}

 

 

   5.dao層(IStudentDAO)

 

package cn.happy.dao;

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

import cn.happy.entity.Student;

public interface IStudentDAO {

    /*
     * 添加學生信息
     */
    public int addStu(Student stu) throws IOException;
    
    /*
     * 查詢所有
     */
    public List<Student> findAll() throws IOException;
    
    /*
     * 模糊查詢
     */
    public List<Student> findAlllike(Student stu) throws IOException;
    
    /*
     * 模糊查詢字符串
     */
    public List<Student> findAlllikebstuname(String stuname) throws IOException;
    
    /*
     * 刪除
     */
    public int delStudent(int id) throws IOException;
}

 

 

   6.dao層下的impl層(IStudentDAOImpl)

 

package cn.happy.dao.impl;

import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import cn.happy.dao.IStudentDAO;
import cn.happy.entity.Student;
import cn.happy.util.MybatisUtil;

public class IStudentDAOImpl implements IStudentDAO{
    
    /*
     * session成員變量
     */
     SqlSession session;

    /*
     * 添加
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#addStu(cn.happy.entity.Student)
     */
    public int addStu(Student stu) throws IOException {
        //獲取session 
        session = MybatisUtil.getSession();
        
        //添加insert
        int result = session.insert("insertStudent", stu);
        
        //添加事物
        session.commit();
        
        //關閉session
        session.close();
        return result;
    }

    /*
     * 查詢所有
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#fandAll()
     */
    public List<Student> findAll() throws IOException {
         //獲取session
         session = MybatisUtil.getSession();
         List<Student> list = session.selectList("findAll");
         //關閉session
         session.close();
         return list;
    }

    /*
     * 模糊查詢
     * 1.參數為對象
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#findAll(cn.happy.entity.Student)
     */
    public List<Student> findAlllike(Student stu) throws IOException {
        //獲取session
         session = MybatisUtil.getSession();
         List<Student> list = session.selectList("findAllLike",stu);
        //關閉session
         session.close();
         return list;
    }
    
    /*
     * 模糊查詢
     * 2.參數為字符串
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#findAll(cn.happy.entity.Student)
     */
    public List<Student> findAlllikebstuname(String stuname) throws IOException {
        //獲取session
         session = MybatisUtil.getSession();
         System.out.println("222");
         List<Student> list = session.selectList("findAllLike",stuname);
         System.out.println("333");
        //關閉session
         session.close();
         return list;
    }

    /*
     * 刪除
     */
    public int delStudent(int id) throws IOException {
         //獲取session
         session = MybatisUtil.getSession();
         int result = session.delete("delStudent", id);
         session.commit();
         return result;
    }

}

 

 

      7.util層的工具類(MybatisUtil )

 

package cn.happy.util;

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 Happy
 *
 */
public class MybatisUtil {
    private static String config="mybatis-config.xml";
    static Reader reader;
    static{
        try {
            reader= Resources.getResourceAsReader(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
    //提供一個可以獲取到session的方法
    public static SqlSession getSession() throws IOException{
        
           // 1.1 openSession到底做了什麼
           SqlSession session = factory.openSession();
           System.out.println("3333");
            return session;
    }
}

 

 

   8. 日志信息配置文件(log4j.properties)

 

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

//記錄cn.happy.dao包下的信息 log4j.logger.cn.happy.dao=trace, stdout

 

 

       暫時就這麼多了,如果想了解更多就記得多多關注吧!!!!

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved