一、mybatis 环境搭建步骤
第一步:创建 maven 工程
第二步:导入坐标
第三步:编写必要代码(实体类和持久层接口)
第四步:编写 SqlMapConfig.xml
第五步:编写映射配置文件
第六步:编写测试类
二、编写sqlMapConfig.xml
xml version="1.0" encoding="UTF-8"?> DOCTYPE configurationPUBLIC "-//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.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/><property name="username" value="root"/><property name="password" value="123456"/>dataSource>environment>environments><mappers><mapper resource="com/jzq/dao/UserDao.xml"/>mappers> configuration>
三、 在持久层(DAO)接口中添加CRUD方法
package com.jzq.dao;import com.jzq.domain.User;import java.util.List;/*** @author jzq* @create 2019-08-24 下午 1:39*/ public interface UserDao {ListfindAll();/*** 保存方法* @param user*/void saveUser(User user);/*** 修改方法* @param user*/void updateUser(User user);/*** 删除方法* @param userId*/void deleteUser(Integer userId);/*** 寻找指定id用户* @param id* @return*/User findUser(Integer id);/*** 模糊查询*/List findByLikeName(String username);/*** 查询总用户数*/int findTotal(); }
四、 在用户的映射配置文件(Mapper)中配置
xml version="1.0" encoding="UTF-8"?> DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jzq.dao.UserDao"><select id="findAll" resultType="com.jzq.domain.User">SELECT * from userselect><insert id="saveUser" parameterType="com.jzq.domain.User"><selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">SELECT last_insert_id();selectKey>INSERT INTO user(username,birthday,sex,address)VALUE (#{username},#{birthday},#{sex},#{address})insert><update id="updateUser" parameterType="com.jzq.domain.User">UPDATE user set username=#{username},sex=#{sex} WHERE id=#{id};update><delete id="deleteUser" parameterType="Integer">DELETE FROM user WHERE id = #{uId}delete><select id="findUser" parameterType="Integer" resultType="com.jzq.domain.User">SELECT * from user WHERE id = #{uid}select><select id="findByLikeName" parameterType="String" resultType="com.jzq.domain.User">SELECT * from user WHERE username like #{name}select><select id="findTotal" resultType="int">SELECT COUNT(id) from user;select> mapper>
五、测试类测试CRUD方法
package com.jzq.test;import com.jzq.dao.UserDao; import com.jzq.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.InputStream; import java.util.Date; import java.util.List;/*** @author jzq* @create 2019-08-24 下午 2:44* CRUD操作*/ public class MyBatisTest {private InputStream in;private SqlSession sqlSession;private SqlSessionFactory factory;private UserDao userDao;@Before//在测试方法执行前执行public void init() throws Exception {//读取配置文件,生成字节输入流in = Resources.getResourceAsStream("SqlMapConfig.xml");//获取sqlSessionFactoryfactory = new SqlSessionFactoryBuilder().build(in);//获取SQLSession对象sqlSession = factory.openSession();//获取dao的代理对象userDao = sqlSession.getMapper(UserDao.class);}@After//在测试方法执行后执行public void destroy() throws Exception {//释放资源 sqlSession.commit();sqlSession.close();in.close();}/*** 测试查询方法** @throws Exception*/@Testpublic void testFindAll() throws Exception {//执行查询所有方法Listusers = userDao.findAll();for (User user : users) {System.out.println(user);}//释放资源 sqlSession.close();in.close();}/*** 测试保存操作*/@Testpublic void testSave() throws Exception {User user = new User();user.setUsername("mybaitis_save");user.setBirthday(new Date());user.setSex("男");user.setAddress("北京市非台区");//执行保存方法 userDao.saveUser(user);sqlSession.commit();}/*** 测试保存操作*/@Testpublic void testFindInsertId() throws Exception {User user = new User();user.setUsername("mybaitis_last insert");user.setBirthday(new Date());user.setSex("女");user.setAddress("北京市台区");System.out.println("执行保存操作之前" + user);//执行保存方法 userDao.saveUser(user);System.out.println("执行保存操作之后" + user);}/*** 测试更新操作*/@Testpublic void testUpdate() throws Exception {User user = new User();user.setId(50);user.setUsername("mybaitis_update");user.setSex("女");//执行查询所有方法 userDao.updateUser(user);}/*** 测试删除操作*/@Testpublic void testDelete() throws Exception {userDao.deleteUser(48);}/*** 测试查找指定操作*/@Testpublic void testFindOne() throws Exception {User user = userDao.findUser(50);System.out.println(user);}/*** 测试模糊查找操作*/@Testpublic void testFindLikeName() throws Exception {List users = userDao.findByLikeName("%小%");for (User user : users) {System.out.println(user);}}/*** 测试查询总用户数*/@Testpublic void testFindTotal(){int count = userDao.findTotal();System.out.println(count);} }