Mybatis简单工程

最近学完mybytis,记录一个简单的工程,从配置环境开始,以便日后查阅

导入依赖

这里是在父工程中(即创建的第一个maven项目,删除src目录,即自动变为父工程,后面的module会自动继承父工程)

  • mysql驱动5.1.47
  • mybatis3.5.2
  • junit4.1.2
  • log4j日志
  • lombok:偷懒用,引用注解后可省去getter,setter等方法
  • build中包含的是为了确保读到java文件夹下的xml和properties文件,resources下的文件可以被自动识别并读取
<?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.fanjh</groupId>
    <artifactId>Mabatis-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-01</module>
        <module>mybatis-02</module>
        <module>mybatis-03</module>
        <module>mybatis-04</module>
        <module>mybatis-05</module>
        <module>mybatis-07</module>
        <module>mybatis-08</module>
        <module>mybatis-09</module>
    </modules>

    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

环境配置

mybatis-config.xml

  • 属性(properties):通过properties来实现引用配置文件
  • 设置(settings):使用标准日志
  • 别名(typeAliases):所有的pojo文件夹下的类都可以使用默认别名
  • 默认事物管理器:JDBC
  • 连接池:POOLED
  • 映射器(mappers):所有的mapper文件都需要注册
<?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">

    </properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <package name="com.fanjh.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>

    <mappers>
        <mapper resource="com/fanjh/dao/StudentMapper.xml"/>
        <mapper resource="com/fanjh/dao/TeacherMapper.xml"/>
    </mappers>

</configuration>

db.properties

这里注意useSSL设置为false

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=xxxxxx

以上都放在resources文件夹下,注意文件夹标记为ResourcesRoot。

编写mybatis工具类

一般都放在utils文件夹下
在这里插入图片描述

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

编写实体类

实体类就根据数据库中的字段名和字段类型进行编写

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}
@Data
public class Student {
    private int id;
    private String name;
    private int tid;

}

编写Mapper接口

mapper接口中定义了对应的实体类的方法,名字上尽量取到和实体类同名,这里是TeacherMapper和StudentMapper。

public interface TeacherMapper {
    //获取指定老师的信息及其所有学生的信息
    List<Teacher> getTeacher(@Param("tid") int id);
}

编写Mapper.xml配置文件

配置文件也是尽量和接口同名,这里是TeacherMapper.xml和StudentMapper.xml,namespace关联到对应的接口

注意!mapper.xml一定要在核心配置文件中注册

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fanjh.dao.TeacherMapper">
    <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="teacherstudent">
        select t.id tid, t.name tname, s.id sid, s.name
        from mybatis.teacher t
        join mybatis.student s
        on t.id = s.tid
        where t.id = #{tid}
    </select>

    <resultMap id="teacherstudent" type="teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>
</mapper>

编写测试类

一切就绪后就可以编写测试类了,测试类放在src.test文件夹下,尽量和接口及对应xml文件在同名文件夹下。

public class MyTest {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

        List<Teacher> teachers = mapper.getTeacher(1);

        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }

        sqlSession.close();
    }
}

首尾的步骤是固定的,得到mapper后就可以使用接口中定义的方法,注意对于CRUD操作,一定要记得提交,否则不会生效:sqlsession.commit()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值