首先是目录结构问题
需要定义接口同时在resource中构建同样的目录使得编译过程让接口和mapper文件在同一目录内
接口中只需要写下定义mapper方法和返回值
public interface StudentMapper {List<student> selectAll();}
mapper中命名空间需要指定为接口的目录
<mapper namespace="top.wjysb.mapper.StudentMapper"><select id="selectAll" resultType="top.wjysb.pojo.student">select *from student;</select></mapper>
需要修改主函数写法
public class mapperDemo {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<student> stu = mapper.selectAll();
System.out.println(stu);
sqlSession.close();
}
}
mybatis中修改写法
<mappers>
<!--加载sql映射文件 -->
<!--<mapper resource="StudentMapper.xml"/>-->
<package name="top.wjysb.mapper"/>
</mappers>
附上修改后的mybatis-config.xml
<?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">
<configuration>
<!-- 配置书写有顺序,具体可以去官网看-->
<!--<typeAliases>
<package name="top.wjysb.pojo"/>
</typeAliases>-->
<!--别名能让mapperxml文件中result少写很多路径,例如top.wjysb.pojo.student可以直接写student-->
<environments default="development">
<!--可以配置多个环境,连接多个数据库,修改default即可快速切换-->
<environment id="development">
<transactionManager type="JDBC"/><!-- 无需修改 -->
<dataSource type="POOLED"><!-- 无需修改 -->
<!--数据库连接信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="yuechan"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件 -->
<!-- <mapper resource="StudentMapper.xml"/>-->
<package name="top.wjysb.mapper"/>
</mappers>
</configuration>
tip 动态sql
