MyBatis配置

第一步加依赖

 <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>

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

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

第二部写配置

建立resources

        建立jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

建立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>
    <!--    读取属性文件(jdbc.properties)
    resources:从resources目录下找指定名称的文件加载
    url:使用绝对路径加载属性文件
    -->
    <properties resource="jdbc.properties"></properties>
<!--    设置日志输出底层执行的代码-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>


    <!--    注册实体类的别名-->
    <typeAliases>
        <!--单个实体类别名注册-->
<!--        <typeAlias type="com.wzx.pojo.Student" alias="student"></typeAlias>-->
        <!--        批量注册
        别名是类名的驼峰命名法(规范)
        -->
        <package name="com.wzx.pojo"/>
    </typeAliases>

    <!--    配置数据库的环境变量(数据库连接配置)
               default:使用下面的environment标签的id属性进行指定配置-->
    <environments default="development">
        <!--   公司
          id:就是提供给environments的default属性使用-->
        <environment id="development">
            <!--            配置事务管理器
                type:指定事务管理的方式
                    JDBC:事务的控制交给程序员处理
                    MANAGED:由容器(SPring)来管理事务
            -->
            <transactionManager type="JDBC"></transactionManager>
            <!--            配置数据源
            type:指定不同的配置方式
                JNDI:Java命名目录接口,在服务器端进行数据库连接池的管理
                POOLED:使用数据库连接池
                UNPOOLED:不适用数据库连接池
            -->
            <dataSource type="POOLED">
                <!--配置数据库连接的基本参数
                private String driver;
                private String url;
                private String username;
                private String password;
                -->
                <property name="driver" value="${jdbc.driverClassName}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
        <!--                &lt;!&ndash;     家里   &ndash;&gt;-->
        <!--                <environment id="home">-->
        <!--                    <transactionManager type=""></transactionManager>-->
        <!--                    <dataSource type=""></dataSource>-->
        <!--                </environment>-->
        <!--                &lt;!&ndash;     上线后   &ndash;&gt;-->
        <!--                <environment id="online">-->
        <!--                    <transactionManager type=""></transactionManager>-->
        <!--                    <dataSource type=""></dataSource>-->
        <!--                </environment>-->
    </environments>
    <!--    注册mapper.xml文件
            resources:从resources目录下找指定名称的文件注册
            url:使用绝对路径注册
            class:动态代理方式下的注册
    -->
    <mappers>
        <mapper resource="StudentMapper.xml"></mapper>
    </mappers>
</configuration>

建立StudengtMapper.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:是整个文件的大标签,用来开始和结束xml文件
    属性:
        namespace:指定命名空间(相当于包名),用来区分不同mapper.xml文件中相同的id属性
-->

<mapper namespace="zar">
    <!--
    完成查询全部学生的功能
        List<Student> getALL();
            resultType:指定查询返回的结果集的类型,如果是集合则必须是泛型的类型
            parameterType:如果有参数,则通过它来指定参数的类型
    -->
    <select id="getAll" resultType="student">
        select id, name, email, age
        from student
    </select>
    <!--
    按主键id查询学生信息
    Student getById(Integer id);
    -->
    <select id="getById" parameterType="int" resultType="student">
        select id, name, email, age
        from student
        where id = #{id}
    </select>
    <!--
    按学生名称模糊查询
    List<Student> getByNmae(String name)
    -->
    <select id="getByName" parameterType="string" resultType="student">
        select id, name, email, age
        from student
        where name like '%${name}%'
    </select>
    <!--
        增加学生
        int insert(Student stu);
        实体类
        private Integer id;
        private String name;
        private String email;
        private Integer age;
    -->
    <insert id="insert" parameterType="student">
        insert into student(name, email, age)
        values (#{name}, #{email}, #{age})
    </insert>
<!--
按主键删除学生
int delete(Integer id);
-->
   <delete id="delete" parameterType="int">
   delete from student where id=#{id}
</delete>
<!--
更新学生
int update(Student stu)
-->
<update id="update" parameterType="student"  >
update student set name=#{name},email=#{email},age=#{age} where id=#{id}
</update>
</mapper>

测试

package com.wzx.test;

import com.wzx.pojo.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 org.junit.Test;

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

public class MyTest {
    @Test
    public void testA() throws IOException {
        //使用文件流读取核心配置文件SqlMapConfig
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //完成查询操作
        List<Student> list = sqlSession.selectList("zar.getAll");
        list.forEach(student -> System.out.println(student));
        //关闭sqlSession
        sqlSession.close();
    }

    @Test
    public void testGetById() throws IOException {
        //读取核心配置文件
        InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出SqlSession
        SqlSession sqlSession = factory.openSession();
        //按主键查学生
        Student stu = sqlSession.selectOne("zar.getById", 1);
        System.out.println(stu);
        //关闭SqlSession
        sqlSession.close();

    }

    @Test
    public void testGetByName() throws IOException {
        //读取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //按主键查学生
        List<Student> list = sqlSession.selectList("zar.getByName", "三");
        list.forEach(student -> System.out.println(student));
        //关闭sqlSession
        sqlSession.close();
    }

    @Test
    public void testInsert() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        int insert = sqlSession.insert("zar.insert", new Student("哈哈", "asdljk", 123));
        //切记切记切记切记:在所有的增删改后必须手动提交事务!!!!
        sqlSession.commit();

        sqlSession.close();

    }
    @Test
    public void testdelete() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        int delete = sqlSession.delete("zar.delete", 6);
        //切记切记切记切记:在所有的增删改后必须手动提交事务!!!!
        sqlSession.commit();
        sqlSession.close();

    }
    @Test
    public void testupdate() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        int delete = sqlSession.update("zar.update", new Student(6,"hehe","jj",12));
        //切记切记切记切记:在所有的增删改后必须手动提交事务!!!!
        sqlSession.commit();
        sqlSession.close();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值