Mybatis学习第二天:Mybatis 增删改查

文章目录

使用代理dao的方式实现增删改查(基本都采用此方式)

为dao接口创建增删改查函数

package com.gegege.dao;

import com.gegege.domain.User;

import java.util.List;

public interface IUserDao {

    /**
     * 查询所有用户
     */
    List<User> findAll();
    /**
     * 插入一个用户
     */
    void installUser(User user);
    /**
     * 更新数据
     */
    void upDateUser(User user);
    /**
     * 删除数据
     */
    void deleteUser(int userid);
    /**
     *根据id查找一个人
     */
    User findById(Integer userid);
    /**
     * 根据姓名模糊查询用户信息
     */
    List<User> findByName(String name);

}

创建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>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>

            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="adminadmin"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/gegege/dao/IUserDao.xml"/>
    </mappers>
</configuration>

创建IUserDao.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.gegege.dao.IUserDao">
    <select id="findAll" resultType="com.gegege.domain.User">
        select
               * from user ;
    </select>
    <insert id="installUser" parameterType="com.gegege.domain.User">
         insert into user (username,address,sex,birthday) values ( #{username},#{address},#{sex},#{birthday} );
    </insert>
    <update id="upDateUser" parameterType="com.gegege.domain.User">
        update user set username=#{username} , address = #{address} , sex=#{sex} ,birthday=#{birthday}
        where id = #{id};
    </update>
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from user where id = #{uid};
    </delete>
    <select id="findById" resultType="com.gegege.domain.User" parameterType="java.lang.Integer">
        select * from user
        where id = #{uid};
    </select>
    <select id="findByName" resultType="com.gegege.domain.User"  parameterType="java.lang.String" >
        select * from user
        where username like #{name};
    </select>
</mapper>

使用test调用

package com.gegege;

import com.gegege.dao.IUserDao;
import com.gegege.domain.User;
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.util.Date;
import java.util.List;
import java.util.Random;

public class mybatis_test {
    private InputStream in;
    private SqlSessionFactoryBuilder sessionFactoryBuilder;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession session;
    private IUserDao dao;
    @Before
    public void before() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建工具
        sessionFactoryBuilder=new SqlSessionFactoryBuilder();
        //创建工厂
        sqlSessionFactory=sessionFactoryBuilder.build(in);
        //生产session
        session=sqlSessionFactory.openSession();
        //使用sqlsession 创建代理对象
        dao=session.getMapper(IUserDao.class);
    }
    @After
    public void after() throws IOException {
        //提交操作
        session.commit();
        //释放资源
        session.close();
        in.close();
    }
    /**
     * 测试查找
     * @throws IOException
     */
    @Test
    public void testFindAll() {
        //调用findall
        List<User> users=dao.findAll();
        for (User user:users
        ) {
            System.out.println(user);
        }
    }

    /**
     * 测试插入
     */
    @Test
    public void testInstall(){
        User user=new User();
        user.setUsername("ddd");
        user.setAddress("aaa");
        user.setBirthday(new Date());
        user.setSex("狗");
        dao.installUser(user);
    }
    /**
     * 测试修改
     */
    @Test
    public void testUpDate() {
        User user=new User();
        int num=new Random().nextInt();
        user.setId(41);
        user.setUsername("ddd"+ num);
        user.setAddress("aaa" + num);
        user.setBirthday(new Date());
        user.setSex("狗");
        dao.upDateUser(user);
    }

    /**
     * 测试删除
     */
    @Test
    public void testdelete() {
        dao.deleteUser(52);
    }
    /**
     * 测试查询一用户
     */
    @Test
    public void testoneuserA() {
        User user = dao.findById(48);
        System.out.println(user);
    }
    /**
     * 测试模糊查询
     */
    @Test
    public void name() {
        List<User> users = dao.findByName("%王%");
        users.forEach(System.out :: println);
    }
}

使用实现类的方式进行增删改查

在原通过代理对象实现的方式修改:

1.创建新的类继承dao接口

这里注意,添加一个session工厂对象,并重写构造方法,传入session工厂,方便下面进行调用

package com.gegege.dao.impl;

import com.gegege.dao.IUserDao;
import com.gegege.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDao implements IUserDao {
    private SqlSessionFactory factory;

    public UserDao() {
    }

    public UserDao(SqlSessionFactory factory){
        this.factory=factory;
    }

    @Override
    public List<User> findAll() {
        //根据factory获取session
        SqlSession session = factory.openSession();
        //调用方法
        List<User> users = session.selectList("com.gegege.dao.IUserDao.findAll");
        //释放资源
        session.close();
        return users;
    }

    @Override
    public void installUser(User user) {
        //根据factory获取session
        SqlSession session = factory.openSession();
        //调用方法实现保存
        session.insert("com.gegege.dao.IUserDao.installUser",user);
        //提交事务
        session.commit();
        //释放资源
        session.close();
    }

    @Override
    public void upDateUser(User user) {

    }

    @Override
    public void deleteUser(int userid) {

    }

    @Override
    public User findById(Integer userid) {
        return null;
    }

    @Override
    public List<User> findByName(String name) {
        return null;
    }
}

2.对测试类进行更改

2.1 先删除session,因为在实现类里传入了session工厂,则session没有作用了

2.2 将dao 改为实例化的方式创建 即new UserDao(sqlSessionFactory);

package com.gegege;

import com.gegege.dao.IUserDao;
import com.gegege.dao.impl.UserDao;
import com.gegege.domain.User;
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.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class mybatis_test {
    private InputStream in;
    private SqlSessionFactoryBuilder sessionFactoryBuilder;
    private SqlSessionFactory sqlSessionFactory;
    private IUserDao dao;
    @Before
    public void before() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建工具
        sessionFactoryBuilder=new SqlSessionFactoryBuilder();
        //创建工
        sqlSessionFactory=sessionFactoryBuilder.build(in);
        //生产session
        //使用sqlsession 创建代理对象
        dao=new UserDao(sqlSessionFactory);
    }
    @After
    public void after() throws IOException {
        //提交操作
        in.close();
    }
    /**
     * 测试查找
     * @throws IOException
     */
    @Test
    public void testFindAll() {
        //调用findall
        List<User> users=dao.findAll();
        for (User user:users
        ) {
            System.out.println(user);
        }
//        int[] num;
//        num.length
    }

    /**
     * 测试插入
     */
    @Test
    public void testInstall(){
        User user=new User();
        user.setUsername("ddd");
        user.setAddress("aaa");
        user.setBirthday(new Date());
        user.setSex("狗");
        dao.installUser(user);
    }
    /**
     * 测试修改
     */
    @Test
    public void testUpDate() {
        User user=new User();
        int num=new Random().nextInt();
        user.setId(41);
        user.setUsername("ddd"+ num);
        user.setAddress("aaa" + num);
        user.setBirthday(new Date());
        user.setSex("狗");
        dao.upDateUser(user);
    }

    /**
     * 测试删除
     */
    @Test
    public void testdelete() {
        dao.deleteUser(52);
    }
    /**
     * 测试查询一用户
     */
    @Test
    public void testoneuser() {
        User user = dao.findById(48);
        System.out.println(user);
    }
    /**
     * 测试模糊查询
     */
    @Test
    public void name() {
        List<User> users = dao.findByName("%王%");
        users.forEach(System.out :: println);
    }

    @Test
    public void tttt() {
    }
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hash=new HashMap<>();
        for (int i=0;i<nums.length;i++){
            hash.put(nums[i],i);
        }
        for (int i=0;i<nums.length;i++){
            int num = target-nums[i];
            if (hash.containsKey(num)){
                int[] o = {i,hash.get(num)};
                return  o;
            }
        }
        return null;
    }
}

properties标签

在SqlMapConfig.xml的使用 <properties resource="jdbcConfig.properties"/>语句来指定配置文件,jdbcConfig.properties文件内容为:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=admin

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">
        <!--mybatis主配置文件-->
<configuration>
    <properties resource="jdbcConfig.properties"/>
<!-- 配置环境 -->
<environments default="mysql">
    <!--配置mysql环境-->
    <environment id="mysql">
        <!--配置事务-->
        <transactionManager type="JDBC"></transactionManager>
        <!--配置数据源(连接池)-->
        <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>
<!--指定映射配置文件,即每个dao独立的配置文件-->
<mappers>
    <mapper resource="com/xiongshou/dao/IUserDao.xml"/>
</mappers>
</configuration>

此时代码仍可正常执行

声明别名

有两种方式配置别名

    <typeAliases>
        <!--声明单个别名-->
<!--        <typeAlias type="com.gegege.domain.User" alias="user" />-->
        <!--声明包,则包下所有类都自动生成别名-->
        <package name="com.gegege.domain"/>
    </typeAliases>


上一篇:Python编程: 局部变量与全局变量


下一篇:周排行、月排行榜开发总结