1、项目目录
可以查看上一篇文章,这里不同的就是IUserDao.xml里面配置的sql语句的信息不同和测试的方法不同。
2、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.mybatis.dao.IUserDao">
<!-- 保存用户-->
<insert id="saveUser" parameterType="com.mybatis.domain.User" >
<!--保存后返回id值-->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into users(username,address,sex,birthday)values (#{username},#{address},#{sex},#{birthday});
</insert>
<!-- 模糊查询-->
<select id="findByName" parameterType="string" resultType="com.mybatis.domain.User">
<!--select * from users where username like "%${value}%";-->
select * from users where username like #{username};
</select>
<!-- 查询总用户数-->
<select id="findTotalUser" resultType="int">
select count(id) from users;
</select>
</mapper>
3、MybatisTest测试类
package com.mybatis.test;
import com.mybatis.dao.IUserDao;
import com.mybatis.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.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class MybatisTest {
private InputStream in;
private SqlSession session;
private IUserDao userDao;
@Before
public void init() throws Exception {
this.in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
System.out.println(in);
SqlSessionFactory factory = factoryBuilder.build(in);
// this.session = factory.openSession(true);
this.session = factory.openSession();
this.userDao = session.getMapper(IUserDao.class);
}
@After
public void destory() throws IOException {
session.commit();
this.in.close();
this.session.close();
}
@Test
public void findByName(){
List<User> users = userDao.findByName("%王%");
for (User user:users){
System.out.println(user);
}
}
@Test
public void findCount(){
int count = userDao.findTotalUser();
System.out.println(count);
}
@Test
public void testSave() throws Exception {
User user = new User();
user.setUsername("admin");
user.setBirthday(new Date());
user.setAddress("背景");
user.setSex("男");
System.out.println(user);
userDao.saveUser(user);
System.out.println(user);
}
}