MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射
我用的idea maven,直接在仓库导入
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version> 3.5.2version>
dependency>
,在这个标签中添加坐标-旁边跳出一个刷新符号,点击自动导入说明 主要配置了数据库连接信息 、注册xml
注意 & 用 &;替换
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://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/girls?user=root&password=root&useUnicode=true&characterEncoding=gbk&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="dao/TestMapper.xml"/>
mappers>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.TestMapper">
<select id="getTestById" resultType="obj.testObj">
select * from test where id = #{id}
select>
mapper>
idea默认的配置文件放在src目录下,如果放在子目录中,则需要加这样几行代码来顺利导出资源
注意 filtering
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
private static SqlSessionFactory sqlSessionFactory = null;
// 通过xml获取 sqlSessionFactory
static {
try (InputStream is = Resources.getResourceAsStream("mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
看起来在调用接口,因为xml已经绑定接口,所以会调用xml中的sql语句
TestMapper tm = ss.getMapper(TestMapper.class);
// 传入参数
List<testObj> list = tm.getTestById(1);
被这个折磨了很久,类用. 文件用/
没有在核心xml注册xml
忘记在pom.xml配置
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>