mybatis(三)mybatis接口与配置文件

同mybatis配置的前三步骤:1.创建java项目,2.导入jar包,3.创建数据库、表、添加数据
一.mybatis配置 mybatis-cofig.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>
    <!-- 配置别名 -->
    <typeAliases>
        <typeAlias type="com.mybatis.all.model.User" alias="user" />
    </typeAliases>
    <!-- 配置环境 -->
    <environments default="development">
        <environment id="development">
        <!-- JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
        <!-- 数据源       驱动、数据库连接、用户名、密码 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test" />
                <property name="username" value="root" />
                <property name="password" value="110119" />
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件 -->
    <mappers>
        <mapper resource="com/mybatis/all/dao/UserInterface.xml" />
    </mappers>
</configuration>

二.创建实体类

/**
 * @author wuchao
 * @time 下午3:14:36
 * @description TODO
 */
package com.mybatis.all.model;

/**
 * @author wuchao
 * @time 下午3:14:36
 * 
 */
public class User {

    private Integer id;
    private String name;
    private String dept;
    private String phone;
    private String website;

    /**
     * @author wuchao
     * @time 下午3:17:43
     */
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @author wuchao
     * @time 下午3:17:49
     */
    public User(Integer id, String name, String dept, String phone,
            String website) {
        super();
        this.id = id;
        this.name = name;
        this.dept = dept;
        this.phone = phone;
        this.website = website;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

}

三.创建接口 UserInterface.java

/**
 * @author wuchao
 * @time 下午3:19:30
 * @description TODO
 */
package com.mybatis.all.dao;

import java.util.List;

import com.mybatis.all.model.User;

/**
 * @author wuchao
 * @time 下午3:19:30
 *映射文件接口  用来做接口注解
 */
public interface UserInterface {

    public User getUserById(int id);
    public List<User> getUserList();
    public void insertUser(User user);
    public void deleteUser(int id);
    public void updateUser(User user);
}

四.创建接口—配置文件 UserInterface.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就是数据操作的接口 -->
<mapper namespace="com.mybatis.all.dao.UserInterface">
    <resultMap type="user" id="getUser">
        <id property="id" column="id" />
        <result property="name" column="name"></result>
        <result property="dept" column="dept"></result>
        <result property="phone" column="phone"></result>
        <result property="website" column="website"></result>
    </resultMap>

    <!-- 通过id查询用户 id为对应接口中的方法 -->
    <select id="getUserById" parameterType="int"
        resultType="com.mybatis.all.model.User">
        select * from user where id = #{id}
    </select>

    <!-- 插入一条user记录 id为对应接口中的方法 -->
    <insert id="insertUser" parameterType="user">
        insert into
        user(name,dept,phone,website) values(#{name},
        #{dept}, #{phone},
        #{website})
    </insert>

    <!-- 查询所有的user List id为对应接口中的方法 -->
    <select id="getUserList" parameterType="user" resultMap = "getUser">
        select * from user
    </select>

    <!-- 更新user id为对应接口中的方法 -->
    <update id="updateUser" parameterType="user">
        update user set name =
        #{name}, dept = #{dept}, phone = #{phone}, website =
        #{website} where
        id = #{id}
    </update>

    <!-- 删除一条记录 id为对应接口中的方法 -->
    <delete id="deleteUser" parameterType="int">
        delete from user where id
        = #{id}
    </delete>
</mapper>

五.创建测试类 test.java

/**
 * @author wuchao
 * @time 上午8:45:30
 * @description TODO
 */
package com.mybatis.all.test;

import java.io.Reader;
import java.text.MessageFormat;
import java.util.List;

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 com.mybatis.all.dao.UserInterface;
import com.mybatis.all.model.User;

/**
 * @author wuchao
 * @time 上午8:45:30
 * 
 */
public class Test {

    // sqlSessionFactory reader
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            // 读取mybatis配置文件
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 创建sqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public static void main(String args[]) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // 用户数据列表
            //getUserList();
            // 插入用户数据
            // insertUser();
            // 通过id查找用户
            // getUserById(2);
            // 更新用户数据
            // User user = new User(1, "zhangsong", "教师", "13811448740",
            // "http://huainanrj.net");
            // updateUser(user);
            //删除用户
            deleteUser(6);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            session.close();
        }

    }

    /**
     * @author wuchao 通过id获取user
     */
    public static User getUserById(int id) {
        User user = new User();
        try {
            System.out.println("开始查询");
            SqlSession session = sqlSessionFactory.openSession();
            UserInterface userInterface = session
                    .getMapper(UserInterface.class);
            System.out.println("进入查询");
            user = userInterface.getUserById(id);
            System.out.println("用户名:" + user.getName());
            System.out.println("角色:"+user.getDept());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 
     * @author wuchao
     * @time 下午12:34:56 插入数据
     */
    public static void insertUser() {
        try {
            SqlSession session = sqlSessionFactory.openSession();
            UserInterface userInterface = session
                    .getMapper(UserInterface.class);
            User user = new User();
            user.setId(2);
            user.setName("jianan");
            user.setDept("xuesheng");
            user.setPhone("110");
            user.setWebsite("www.sina.com.cn");
            userInterface.insertUser(user);
            System.out.println("用户名:" + user.getName());
            session.commit();
            getUserList();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * @author wuchao 获取user列表
     */
    public static List getUserList() {
        try {
            SqlSession session = sqlSessionFactory.openSession();
            UserInterface userInterface = session
                    .getMapper(UserInterface.class);
            System.out.println("====开始查询列表======");
            printUsers(userInterface.getUserList());
            System.out.println("查询结束");
            /*
             * List<User> userList = userInterface.getUserList(); for (User user
             * : userList) { System.out.println("用户id:" + user.getId() + "用户名字:"
             * + user.getName() + "用户部门:" + user.getDept() + "用户电话:" +
             * user.getPhone() + "用户网站:" + user.getWebsite());
             * 
             * }
             */
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @author wuchao 更新User
     */
    public static void updateUser(User user) {
        try {
            SqlSession session = sqlSessionFactory.openSession();
            UserInterface userInterface = session
                    .getMapper(UserInterface.class);
            getUserList();
            // user = userInterface.getUserById(1);
            user.setName("吴超");
            userInterface.updateUser(user);
            session.commit();
            getUserList();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * @author wuchao 删除用户
     */
    public static String deleteUser(int id) {
        try {
            SqlSession session = sqlSessionFactory.openSession();
            UserInterface userInterface = session
                    .getMapper(UserInterface.class);
            userInterface.deleteUser(6);
            session.commit();
            getUserList();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return "删除成功";
    }

    /**
     * @author wuchao
     */
    public static void printUsers(final List<User> users) {
        int count = 0;
        for (User user : users) {
            System.out.println(MessageFormat.format("=====User[{0}]====",
                    ++count));
            System.out.println("User id" + user.getId());
            System.out.println("User name" + user.getName());
            System.out.println("User dept" + user.getDept());
            System.out.println("User phone" + user.getPhone());
            System.out.println("User website" + user.getWebsite());
        }
    }
}

六.项目结构图与测试结果
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值