mybatis实现简单的查询
1.导入相关的依赖
- mybatis
- mysql
- log4j日志
- lombok可以省略类的许多方法
2.编写持久层接口
package com.kfm.mybatis.mapper;
import com.kfm.mybatis.model.Allfile;
import java.util.List;
/**
* @author jkk
*/
public interface IAllfileMapper {
List<Allfile> selectAll();
}
3.编写持久层映射文件
mapper是映射的意思,其映射的内容就是对应的持久层接口
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTO Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kfm.mybatis.mapper.IAllfileMapper">
<select id="selectAll" resultType="com.kfm.mybatis.model.Allfile">
select * from file
</select>
</mapper>
4.编写配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/web"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/kfm/mybatis/mapper/IAllfileMapper.xml"/>
</mappers>
</configuration>
5.写测试用例
package com.kfm.mybatis.mapper;
import com.kfm.mybatis.model.Allfile;
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.List;
import static org.junit.Assert.*;
public class IAllfileMapperTest {
InputStream inputStream;
SqlSessionFactory factory;
SqlSession session;
@Before
public void before() throws IOException {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
factory = sqlSessionFactoryBuilder.build(inputStream);
session = factory.openSession();
}
@After
public void after() throws IOException {
session.close();
inputStream.close();
}
@Test
public void selectAll() throws IOException {
IAllfileMapper mapper = session.getMapper(IAllfileMapper.class);
List<Allfile> allfiles = mapper.selectAll();
for (Allfile allfile :allfiles){
System.out.println(allfile);
}
}
}