MyBatis Demo

MyBatis Demo

项目目录总览:

lc0rX.png

1.向pom.xml中导入依赖

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.在resources文件夹中创建mybatis-config.xml、db.properties

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 resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.ssm.mybatis.dao"/> 
    </mappers>
</configuration>

!!需要改package中的name,改为自己所建的dao包,例如:×××.××.××.dao

db.properties内容:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/chapter03?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = ****

需要该为自己的数据库名字,把chapter03换为自己的数据库,和改username、password

3.分别建立三个包dao、pojo、utils

首先utils包中的MyBatisUtils类可以不用变直接粘贴下列代码

package com.ssm.mybatis.utils;

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.Reader;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession()
    {
        return sqlSessionFactory.openSession();
    }
}

pojo中的类要根据所给的信息,来和数据库中的表来相互关联,一张表对应一个类,要注意在一对多关系中,在一那个类中创建多那个类的集合。

Student类代码如下:

package com.ssm.mybatis.pojo;

public class Student {
    private int sid;
    private String sname;
    private String age;
    private String course;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age='" + age + '\'' +
                ", course='" + course + '\'' +
                '}';
    }
}

StuClass类代码如下:

package com.ssm.mybatis.pojo;

import java.util.List;

public class StuClass {
    private int cid;
    private String cname;
    private int sum;
    private List<Student> stuList;

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }

    public List<Student> getStuList() {
        return stuList;
    }

    public void setStuList(List<Student> stuList) {
        this.stuList = stuList;
    }

    @Override
    public String toString() {
        return "StuClass{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                ", sum=" + sum +
                ", stuList=" + stuList +
                '}';
    }
}

最后在dao包中创建mapper

IStudentMapper接口代码如下:

package com.ssm.mybatis.dao;

import com.ssm.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface IStudentMapper {
    @Select("select * from stu_info where sid= #{sid}")
    @Results({@Result(id = true, column = "sid", property = "sid"),
            @Result(column = "sname", property = "sname"),
            @Result(column = "age", property = "age"),
            @Result(column = "course", property = "course")})
    public Student selectStudentById(int id);

    @Update("update stu_info set sname = #{sname}, age = #{age} where sid = #{sid}")
    public int updateStudent(Student student);

    @Select("select * from stu_info where classid = #{cid}")
    public List<Student> selectStudentByCid(int cid);
}

IStuClassMapper接口代码如下:

package com.ssm.mybatis.dao;

import com.ssm.mybatis.pojo.StuClass;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface IStuClassMapper {
    @Select("select * from stu_class where cid= #{cid}")
    @Results({ @Result(id = true, column = "cid", property = "cid"),
            @Result(column = "cname", property = "cname"),
            @Result(column = "sum", property = "sum"),
            @Result(column = "cid", property = "stuList",
                    many = @Many(
                            select = "com.ssm.mybatis.dao.IStudentMapper.selectStudentByCid"
                    )
            )
    })
    public StuClass selectStudentByClassId(int id);
}

4.最后在与main同级的test次级目录绿色的java中创建个test包中创建MyBatisTest类来进行测试

需要注意的是要在方法名上方加上给@Test注解,这些方法如findStudentById都是随意起的名字

MyBatisTest类代码如下:

package test;

import com.ssm.mybatis.dao.IStuClassMapper;
import com.ssm.mybatis.dao.IStudentMapper;
import com.ssm.mybatis.pojo.StuClass;
import com.ssm.mybatis.pojo.Student;
import com.ssm.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyBatisTest {
    @Test
    public void findStudentById(){
        SqlSession session = MyBatisUtils.getSession();
        IStudentMapper iStudentMapper = session.getMapper(IStudentMapper.class);
        Student student = iStudentMapper.selectStudentById(1);
        System.out.println(student.toString());
        session.close();
    }

    @Test
    public void findStudentByCid(){
        SqlSession session = MyBatisUtils.getSession();
        IStuClassMapper iStuClassMapper = session.getMapper(IStuClassMapper.class);
        StuClass stuClass = iStuClassMapper.selectStudentByClassId(1);
        List<Student> students = stuClass.getStuList();
        for(Student student : students){
            System.out.println(student.toString());
        }
        session.close();
    }

    @Test
    public void updateStudentById(){
        SqlSession session = MyBatisUtils.getSession();
        IStudentMapper iStudentMapper = session.getMapper(IStudentMapper.class);
        Student student = new Student();
        student.setSid(1);
        student.setSname("lihao");
        student.setAge("20");
        System.out.println(student);
        int cnt = iStudentMapper.updateStudent(student);
        if(cnt > 0){
            System.out.println("update successful!");
        }
        session.commit();
        session.close();
    }
}

5.结束,应该能拿不少分数了😎

posted @ 2022-05-23 23:17  wei_good  阅读(164)  评论(0编辑  收藏  举报