dao层的创建
(1)创建dao包,如:
(2)根据先前定义的实体类,定义出接口,如:
上图中定义出的接口主要是增删改查操作:(1)返回所有用户信息(2)根据用户名返回用户信息(3)插入用户信息(4)更新用户信息(5)根据用户名删除用户信息。
创建UserDao对应的Mapper文件
(1)在resources下创建mapper文件夹,如:
(2)在mapper文件夹下创建对应于实体类的mapper文件,如上图中的UserDao.xml即对应实体类User。
mapper文件中配置着我们的增删改查的数据操作语句,由框架扫描后进行调用,此处贴出源码示例如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/schema/mybatis-3-mapper.dtd">
<!--namespace为我们定义的数据表操作接口的完整路径-->
<mapper namespace="com.example.mybatistest.dao.UserDao">
<!--id为接口中定义的方法名;resultType为数据表对应实体类的完整路径-->
<!--当查询返回的结果为复数个时,框架会自动为我们做处理,无需担心,用List接收便是-->
<select id="queryUser" resultType="com.example.mybatistest.entity.User">
<!--里面是select语句-->
SELECT *
FROM user_tb
</select>
<select id="queryUserByName" resultType="com.example.mybatistest.entity.User">
SELECT *
FROM user_tb
WHERE
username=#{username}
</select>
<!--useGeneratedKeys="true"表示如果一旦Insert成功就返回一个主键的值,
返回的主键由keyProperty指定,keyColumn指定主键(即keyProperty)对应的column-->
<!--parameterType指定传入参数的类型-->
<!--#{}表示引用参数的值,其名即为实体类中定义的属性名-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="username" keyColumn="username" parameterType="com.example.mybatistest.entity.User">
INSERT INTO
user_tb(username,password)
VALUES
(#{username},#{password})
</insert>
<!--在<set>标签中,以<if>标签判断属性是否为空,不为空则重新赋值-->
<update id="updateUser" parameterType="com.example.mybatistest.entity.User">
update user_tb
<set>
<if test="username!=null">username=#{username},</if>
<if test="password!=null">password=#{password}</if>
</set>
where username=#{username}
</update>
<delete id="deleteUser">
DELETE FROM
user_tb
WHERE
username=#{username}
</delete>
</mapper>
编写单元测试类
windows下idea快捷键:(1)alt + enter;(2)alt + insert.
此处使用alt + enter生成单元测试类,如:
创建出测试类时,当我们写入如下代码:
@Autowired
private UserDao userDao;
报错提示:Could not autowire. No beans of ‘UserDao’ type found
可以采用如下解决方法:
写出的测试类如下:
package com.example.mybatistest.dao;
import com.example.mybatistest.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest{
/**
* 报错提示“Could not autowire. No beans of 'UserDao' type found”
* 解决方法:
*
*/
@Autowired
private UserDao userDao;
@Test
public void queryUser() {
List<User> userList = userDao.queryUser();
assertEquals(2, userList.size());
}
@Test
public void queryUserByName() {
}
@Test
public void insertUser() {
}
@Test
public void updateUser() {
}
@Test
public void deleteUser() {
}
}
关于启动测试时报错:[classpath*:/mapper/*.xml] cannot be opened because it does not exist
解决方法:
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置mybatis-config配置文件扫描路径
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
//设置mapper文件扫描路径
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
//设置dataSource
sqlSessionFactoryBean.setDataSource(dataSource);
//映射实体类,指定实体类包的扫描路径
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
在这个代码中,一定一定一定一定一定注意,千万不要把sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
中的resolver.getResources(xxx)写成resolver.getResource(xxx)!!!!!!!!!!!!!!
启动测试,运行成功如:
继续来完善这个dao层代码,此处贴出完整测试代码如下:
package com.example.mybatistest.dao;
import com.example.mybatistest.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest{
/**
* 报错提示“Could not autowire. No beans of 'UserDao' type found”
* 解决方法:
*
*/
@Autowired
private UserDao userDao;
@Test
public void queryUser() {
List<User> userList = userDao.queryUser();
assertEquals(2, userList.size());
}
@Test
public void queryUserByName() {
User user = userDao.queryUserByName("xxx");
assertEquals("xxx",user.getPassword());
}
@Test
public void insertUser() {
User user = new User();
user.setUsername("yyy");
user.setPassword("yyy");
//该返回值会返回影响的行数
int rows = userDao.insertUser(user);
assertEquals(1,rows);
}
@Test
public void updateUser() {
User user = new User();
user.setUsername("xxx");
user.setPassword("bbb");
int rows = userDao.updateUser(user);
assertEquals(1,rows);
}
@Test
public void deleteUser() {
int rows = userDao.deleteUser("xxx");
assertEquals(1,rows);
}
}