Mybatis通用模板

  1. 目录结构:
    在这里插入图片描述

  2. pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com</groupId>
    <artifactId>jcg2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>


    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>

</project>
  1. log4j.properties
log4j.rootCategory=debug, CONSOLE, LOGFILE

log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30C %x - %m\n
  1. SqlMapConfig.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 resource="jdbcConfig.properties"></properties>
    <!-- 使用typeAliases配置别名  它只能配置domain中类的别名 -->
    <typeAliases>
        <package name="com.domain"></package>
    </typeAliases>

    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>

    <!--配置映射文件的位置-->
    <mappers>
        <package name="com.dao"></package>
    </mappers>

</configuration>


  1. SiteDao.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="com.dao.SiteDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.Site">
        select * from sites;
    </select>

</mapper>

  1. 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="com.dao.StudentDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.Student">
        select * from students;
    </select>

</mapper>

  1. Site
package com.domain;

public class Site {

    private int site_id;
    private String site_web;

    @Override
    public String toString() {
        return "Site{" +
                "site_id=" + site_id +
                ", site_web='" + site_web + '\'' +
                '}';
    }

    public Site(int site_id, String site_web) {
        this.site_id = site_id;
        this.site_web = site_web;
    }

    public int getSite_id() {
        return site_id;
    }

    public void setSite_id(int site_id) {
        this.site_id = site_id;
    }

    public String getSite_web() {
        return site_web;
    }

    public void setSite_web(String site_web) {
        this.site_web = site_web;
    }
}

  1. Student
package com.domain;

public class Student {
    private int studnet_id;
    private String student_name;
    private String student_sex;

    @Override
    public String toString() {
        return "Student{" +
                "studnet_id=" + studnet_id +
                ", student_name='" + student_name + '\'' +
                ", student_sex='" + student_sex + '\'' +
                '}';
    }

    public Student(int studnet_id, String student_name, String student_sex) {
        this.studnet_id = studnet_id;
        this.student_name = student_name;
        this.student_sex = student_sex;
    }

    public int getStudnet_id() {
        return studnet_id;
    }

    public void setStudnet_id(int studnet_id) {
        this.studnet_id = studnet_id;
    }

    public String getStudent_name() {
        return student_name;
    }

    public void setStudent_name(String student_name) {
        this.student_name = student_name;
    }

    public String getStudent_sex() {
        return student_sex;
    }

    public void setStudent_sex(String student_sex) {
        this.student_sex = student_sex;
    }
}

  1. SiteDao
package com.dao;

import com.domain.Site;

import java.util.List;

public interface SiteDao {

    List<Site> findAll();
}

  1. StudentDao
package com.dao;

import com.domain.Student;

import java.util.List;

public interface StudentDao {
    List<Student> findAll();
}

  1. Main
package com;

import com.dao.SiteDao;
import com.dao.StudentDao;
import com.domain.Site;
import com.domain.Student;
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.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Main {

    //student列表
    public List<Student> studentList =  new ArrayList<Student>();
    //site列表
    public List<Site> siteList =  new ArrayList<Site>();

    private InputStream in;
    private SqlSession sqlSession;
    private StudentDao studentDao;
    private SiteDao siteDao;

//    @Before//用于在测试方法之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        studentDao = sqlSession.getMapper(StudentDao.class);

        siteDao = sqlSession.getMapper(SiteDao.class);

    }

//    @After//用于在测试方法之后执行
    public void destory()throws Exception{
        //5.提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }


    public void testStudentFindAll(){
        studentList = studentDao.findAll();
        for(Student student: studentList){
            System.out.println(student);
        }
    }

    public void testSiteFindAll(){
        siteList = siteDao.findAll();
        for(Site site: siteList){
            System.out.println(site);
        }
    }

    //生成随机数据
    public void generateRandomData(){
        //获取两个列表的长度
        int studentListLen = studentList.size();
        int siteListLen = siteList.size();


        //获取一个随机数字
        int randomStudent = (int)(Math.random()*(studentListLen));
        int randomSite = (int)(Math.random()*(siteListLen));

        Student stu = studentList.get(randomStudent);
        System.out.println(stu);
        Site site = siteList.get(randomSite);
        System.out.println(site);

        try{
            File file =new File("data.txt");
            //if file doesnt exists, then create it
            if(!file.exists()){
                file.createNewFile();
            }
            //true = append file
            FileWriter fileWritter = new FileWriter(file.getName(),true);
            fileWritter.write(stu.toString()+"\t"+site.toString()+"\n");
            fileWritter.close();

            System.out.println("Done");
        }catch(IOException e){
            e.printStackTrace();
        }
    }


    public static void main(String[] args)throws Exception {
        Main jcg = new Main();

        jcg.init();

        jcg.testStudentFindAll();

        jcg.testSiteFindAll();

        jcg.generateRandomData();

        jcg.destory();


    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值