MyBatis动态代理配置

本文介绍了如何通过步骤配置Mybatis,包括添加Mysql和Mybatis依赖,配置jdbc.properties和SqlMapConfig.xml,实现数据库连接和操作。接着展示了实体类Users的定义,接口UserMapper的编写,以及测试类中的关键功能测试。
摘要由CSDN通过智能技术生成

第一步添加依赖

   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.9</version>
          <scope>test</scope>
<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里面建立

        1.jdbc.properties

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

        2.建立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属性-->
    <properties resource="jdbc.properties"></properties>
    <!--设置日志输出-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--注册实体类别名  -->
    <typeAliases>
        <package name="com.wzx.pojo"></package>
    </typeAliases>
    <!--配置环境变量-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <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>
    </environments>
    <!--注册mapper.xml -->

    <mappers>
        <package name="com.wzx.mapper"></package>
    </mappers>

</configuration>

 第三步

        建立实体Users

package com.wzx.pojo;

import java.util.Date;

public class Users {
    /**
     *
     */
    private Integer id;

    /**
     * 用户名称
     */
    private String userName;

    /**
     * 生日
     */
    private Date birthday;

    /**
     * 性别
     */
    private String sex;

    /**
     * 地址
     */
    private String address;

    public Users() {
    }

    public Users(String userName, Date birthday, String sex, String address) {
        this.userName = userName;
        this.birthday = birthday;
        this.sex = sex;
        this.address = address;
    }

    public Users(Integer id, String userName, Date birthday, String sex, String address) {
        this.id = id;
        this.userName = userName;
        this.birthday = birthday;
        this.sex = sex;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

第四步创建接口

        动态代理要求

        接口与Mapper文件要相同的名字,相同的包

        建立UserMapper接口与UserMapper.xml

接口代码

package com.wzx.mapper;

import com.wzx.pojo.Users;

import java.util.List;

/**
 * 数据访问层的接口,规定数据库中可进行的各种操作
 */
public interface UserMapper {
    //查询去拿不用户信息
    List<Users>  getAll();
    //根据用户主键查用户
    Users getById(Integer id);
    //根据用户名模糊查询用户
    List<Users> getByName(String name);
    //用户的更新
   int update(Users users);
    //根据主键删除用户
    int delete(Integer id);
    //增加用户
    int insert(Users users);

}

Usermapper.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.wzx.mapper.UserMapper">
    <select id="getAll" resultType="users">
        select id, username, birthday, sex, address
        from users
    </select>
    <!--     private Integer id;
        private String userName;
        private Date birthday;
        private String sex;
        private String address;-->
    <update id="update" parameterType="users">
        update users
        set username=#{userName},
            birthday=#{birthday},
            sex#{sex},
            address#{address}
        where id = #{id}
    </update>
    <select id="getById" parameterType="int" resultType="users">
        select id, username, birthday, sex, address
        from users
        where id = #{id}
    </select>
    <select id="getByName" parameterType="string" resultType="users">
        select id, username, birthday, sex, address
        from users
        where username like '%${userName}%'
    </select>
    <delete id="delete" parameterType="users">
        delete
        from users
        where id = #{id}
    </delete>
    <insert id="insert" parameterType="users">
        insert into (id,username,birthday,sex,address) values (#{id},#{userName},
                #{birthday},
                #{sex},
                #{address} )
    </insert>
</mapper>

 测试类

package com.wzx;

import com.wzx.mapper.UserMapper;
import com.wzx.pojo.Users;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MyTest {

    SqlSession sqlSession;
    UserMapper mapper;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

    @Before
    public void openSqlSession() throws IOException {
        //读取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出SqlSession对象
        sqlSession = factory.openSession();
        //取出动态代理的对象,完成接口中方法的调用,实则是使用xml文件中的标签的功能
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void closeSqlSession() {
        sqlSession.close();
    }

    @Test
    public void testGetAll() {
        //  就是在调用接口的方法,mybatis框架已经为我们把功能代理出来了
        List<Users> list = mapper.getAll();
        System.out.println(list);
        list.forEach(users -> System.out.println(users));
    }

    @Test
    public void testupdate() throws ParseException {
        Users u = new Users(7, "wzx", sf.parse("2001-01-01"), "2", "asd");
        int update = mapper.update(u);
        System.out.println(update);
        sqlSession.commit();

    }

    @Test
    public void selectById() {
        Users byId = mapper.getById(7);
        System.out.println(byId);

    }
    @Test
    public void getByName(){
        List<Users> name = mapper.getByName("张");
        name.forEach(users -> System.out.println(users));
    }
    @Test
    public void delete(){
        int delete = mapper.delete(7);
        System.out.println(delete);
        sqlSession.commit();
    }
    @Test
    public void insert() throws ParseException {
        Users users = new Users(8, "asd", sf.parse("2022-11-22"), "1", "asd");
        int insert = mapper.insert(users);
        System.out.println(insert);
        sqlSession.commit();
    }
}

不足:更新与添加的sql语句不知道为什么老是报错,以后自己找到了来这里更改

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值