创建数据库表的映射类
//数据库中有多少字段对应类有多少属性,不然会报错 @Data //lombok的注解,用此注解可以不用对属性的getter和setter方法进行重写 public class User { private String id; private String name; private String age; }创建 UserMapper 类
@Mapper public interface UserMapper { //@Param 对传入的数据进行绑定,当参数为一个时,可以选择不加注解 //根据id查询用户信息 public User getInfo(@Param("id") String id); //查询数据库所有的用户信息 List<User> findAll(); //增加一条用户信息 boolean insert(User user); //根据用户id更新用户信息 boolean updateUser(User user); //根据用户id删除用户信息 boolean removeById(String id); //模糊查询 List<User> findByName(String username); }
在 resource/mapper 文件下创建 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类的路径一致--> <mapper namespace="com.yiying.mapper.UserMapper"> <!--根据id查询用户信息--> <select resultType="com.yiying.entity.User" parameterType="java.lang.String"> SELECT id, name,age FROM user WHERE id = #{id} </select> <resultMap type="user"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> </resultMap> <!--查询所有用户信息--> <select resultMap="userMap" useCache="true"> select * from user </select> <!--模糊查询--> <select resultType="com.yiying.entity.User"> select * from user where name like '%${name}%' </select> <!--添加一条记录--> <insert parameterType="com.yiying.entity.User"> insert into user(id,name,age) values(#{id},#{name},#{age}) </insert> <!--根据用户id修改用户信息--> <update parameterType="com.yiying.entity.User"> update user set name=#{name},age=#{age} where id = #{id} </update> <!--根据用户id删除用户--> <delete parameterType="java.lang.String"> delete from user where id = #{id} </delete> </mapper>
对增删改查操作进行测试
// 首先需要在 test 文件夹中创建测试类 //在处理测试时,先加载 init() 处理完测试后,加载 destory() //在执行方法前执行 @Before public void init() throws Exception { //1.读取配置文件 in = Resources.getResourceAsStream("mybatis-config.xml"); //2.创建构建者对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //3.创建 SqlSession 工厂对象 factory = builder.build(in); //4.创建 Dao 接口的实现类 sqlSession = factory.openSession(); //5.创建代理对象 userMapper= sqlSession.getMapper(UserMapper.class); } /** * 执行完方法后执行 */ @After public void destory(){ sqlSession.commit(); try { sqlSession.close(); //释放资源 in.close(); } catch (IOException e) { e.printStackTrace(); } } //查询 public class Test { private InputStream in; private SqlSessionFactory factory; SqlSession sqlSession; private UserMapper userMapper; //根据id查询 @Test public void test1(){ User user = userMapper.getInfo("1"); System.out.println(user); } @Test public void test2(){ List<User> userList = userMapper.findAll(); System.out.println("查询的所有数据:" + userList.toString()); } //模糊查询 @Test public void test3(){ List<User> user = userMapper.findByName("张三"); System.out.println("根据名字模糊查询结果为:"+user.toString()); } }