mybatis入门
2021-04-02
- 写mybatis配置文件
<?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>
<!--数据库配置文件路径-->
<!--<properties resource="config.properties"/>-->
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--映射文件位置-->
<mappers>
<mapper resource="space/xiaoxiang/dao/XxxxMapper.xml"/>
<!--<package name="space.xiaoxiang.dao"/> 使用package接口的包名必须与xml包名一样-->
</mappers>
</configuration>
- 数据库配置文件config.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxxxx?serverTimezone=GMT%2B8&characterEncoding=utf-8
username=xxxx
password=xxxxxxxx
-
写dao层接口和xml文件
- 接口
package space.xiaoxiang.dao; import java.util.List; import java.util.Map; public interface XxxxMapper { public List<Map<String, Object>> selectAll(); }
- 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="space.xiaoxiang.dao.XxxxtMapper"> <select id="selectAll" resultType="map"> SELECT * FROM xxxx </select> </mapper>
-
运行
@Test
public void test() throws IOException {
//数据库配置文件
String databaseConfigFileName = "config.properties";
Properties databaseConfig = new Properties();
databaseConfig.load(Resources.getResourceAsStream(databaseConfigFileName));
//mybatis配置文件
String mybatisConfigFileName = "mybatis-config.xml";
InputStream mybatisConfig = Resources.getResourceAsStream(mybatisConfigFileName);
//一个数据库对应一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfig,databaseConfig);
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
XxxxMapper xxxxMapper = sqlSession.getMapper(XxxxMapper.class);
xxxxMapper.selectAll().forEach((map) -> {
xxxxMapper.forEach((k, v) -> {
System.out.println(k + " : " + v);
});
});
}
}