mybatis 基本用法
先进行全局配置 SqlMapConfig.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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> <!--配置环境--> <environments default="mysql"> <!--配置mysql的环境--> <environment id="mysql"> <!--配置事务类型--> <transactionManager type="JDBC"></transactionManager> <!--配置数据源(连接池)--> <dataSource type="POOLED"> <!--配置连接数据库4个基本信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis?serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="nimahaoma49"/> </dataSource> </environment> </environments> <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件--> <mappers> <mapper resource="com/itheima/dao/IUserDao.xml"/> </mappers> </configuration>
首先定义好一个User类,和数据库里的user表相对应
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private Integer id; private String username; private Date birthday; private String sex; private String address; @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
定义一个QueryVo类用于对象封装的查询
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.domain; public class QueryVo { private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
定义好一个用来操作数据库的接口IUserDao
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.dao; import com.itheima.domain.QueryVo; import com.itheima.domain.User; import java.util.List; public interface IUserDao { /* * 查询所有操作 * */ List<User> findAll(); /* * 保存一条记录并返回id(直接将id赋给对应的属性) * */ void saveUser(User user); /* * 更新用户 * */ void updateUser(User user); /* * 删除用户 * */ void deleteUser(Integer userId); /* * 根据Id查询User * */ User findById(Integer userId); /* * 模糊查询 * */ List<User> findByName(String username); /* * 查询User总数 * */ int findTotal(); /* * 根据queryVo查询中的条件查询用户 * */ List<User> findByVo(QueryVo vo); }
编写 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.itheima.dao.IUserDao"> <!--当表列名和实体类的属性名不同时,配置列名和实体类属性名的对应关系,同时,要把下面使用这个配置的resultType改成resultMap--> <resultMap id="userMap" type="com.itheima.domain.User"> <!--主键字段的对应--> <id property="id" column="id"></id> <!--非主键字段的对应--> <result property="username" column="username"></result> <result property="address" column="address"></result> <result property="sex" column="sex"></result> <result property="birthday" column="birthday"></result> </resultMap> <!--配置查询所有--> <select id="findAll" resultMap="userMap"> select id as id,username as username, address as address,sex as sex, birthday as birthday from user; </select> <!--保存一条记录--> <insert id="saveUser" parameterType="com.itheima.domain.User"> <!--插入后,获取插入数据的id keyColumn对应表的列名,keyProperty对应实体类的属性--> <selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER"> select last_insert_id(); </selectKey> insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday}); </insert> <!--更新用户--> <update id="updateUser" parameterType="com.itheima.domain.User"> update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}; </update> <!--删除用户--> <delete id="deleteUser" parameterType="Integer"> delete from user where id = #{userId} </delete> <!--根据id查询User--> <select id="findById" parameterType="int" resultType="com.itheima.domain.User"> select * from user where id = #{id}; </select> <!--根据username模糊查询User--> <select id="findByName" parameterType="String" resultType="com.itheima.domain.User"> select * from user where username like #{username} </select> <!--获取用户的总记录条数--> <select id="findTotal" resultType="int"> select count(*) from user ; </select> <!--根据queryVo的条件查询用户--> <select id="findByVo" parameterType="com.itheima.domain.QueryVo" resultType="com.itheima.domain.User"> select * from user where username like #{user.username}; </select> </mapper>
使用(测试)前的准备工作
private InputStream in = null; private SqlSession session = null; private IUserDao userDao = null; @Before //用于测试前执行 public void init()throws Exception{ //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建SQLSessionFactory对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); //3.使用工厂生成SqlSession对象 session = factory.openSession(); //4.使用SqlSession创建Dao接口的代理对象 userDao = session.getMapper(IUserDao.class); } @After //用于测试后执行 public void destory() throws IOException { //6.提交事务,释放资源 session.commit(); session.close(); in.close(); }
测试
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Test public void testFindAll()throws Exception{ //5.使用代理对象执行方法 List<User>users = userDao.findAll(); for(User user:users) System.out.println(user); } @Test public void testSave() throws IOException { User user = new User(); user.setUsername("mybatis testsave3"); user.setAddress("北京市顺义区3"); user.setSex("男"); user.setBirthday(new Date()); System.out.println(user); //5.使用代理对象执行方法 userDao.saveUser(user); System.out.println(user); } @Test public void testUpdate(){ User user = new User(); user.setId(50); user.setUsername("mybatis testUpdate"); user.setAddress("北京市顺义区"); user.setSex("女"); userDao.updateUser(user); } @Test public void testDelete(){ userDao.deleteUser(48); } @Test public void testFindById(){ User user = userDao.findById(50); System.out.println(user); } @Test public void testFindByName(){ List<User> users = userDao.findByName("%王%"); for(User user:users) System.out.println(user); } @Test public void testFindTotal(){ int count = userDao.findTotal(); System.out.println(count); } @Test public void testFindByVo(){ QueryVo vo = new QueryVo(); User user = new User(); user.setUsername("%王%"); vo.setUser(user); List<User> users = userDao.findByVo(vo); for(User user1:users) System.out.println(user1); }