package com.kuang.dao; import com.kuang.pojo.User; import java.util.List; public interface UserMapper { List<User>getUserList(); //根據id查詢用戶 User getUserById(int id); //插入一個用戶 int addUser(User user); //修改用戶信息 void updateUser(User user); //刪除用戶信息 int deleteUser(int id); }
<?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.kuang.dao.UserMapper"> <select id="getUserList" resultType="com.kuang.pojo.User"> select * from mybaits.user; </select> <select id="getUserById" resultType="com.kuang.pojo.User" parameterType="int"> select *from mybaits.user where id=#{id} </select> <insert id="addUser" parameterType="com.kuang.pojo.User" > insert into mybaits.user(id, name, password) values (#{id},#{name},#{password}); </insert> <update id="updateUser" parameterType="com.kuang.pojo.User" > update mybaits.user set name=#{name}, password=#{password} where id=#{id}; </update> <delete id="deleteUser" parameterType="int"> delete from mybaits.user where id=#{id} </delete> </mapper>
**namespace中寫xml文件的絕對路徑
id填方法名 注意要和接口中的方法名一致 不能有空格!!!
resultType寫實體類的絕對路徑**java
@Test public void test(){ //獲取sqlsession實例對象 //SqlSession 提供了在數據庫執行 SQL 命令所需的全部方法 SqlSession sqlSession = MybatisUtils.getSqlSession(); //經過映射類並將已映射的 select 語句匹配到對應名稱、參數和返回類型的方法 UserMapper userDao = sqlSession.getMapper(UserMapper.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } //關閉流 sqlSession.close();