mybatis基础 笔记
Mybatis依赖
<!--测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
mybatis-config.xml(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">
<!-- 通过这个配置文件完成mybatis与数据库的连接 -->
<configuration>
<!-- 引入 database.properties 文件-->
<properties resource="database.properties"/>
<!-- 配置mybatis的log实现为LOG4J -->
<settings>
<setting name="logImpl" value="LOG4J" />
<!--设置resultMapper自动映射为NONE(禁止自动匹配 UserMapper.xml里面的只输出<resultMap>内包含的)-->
<setting name="autoMappingBehavior" value="NONE"/>
</settings>
<typeAliases>
<!--扫描该包下的所有实体类 起别名-->
<package name="保存实体类的包url"/>
</typeAliases>
<!--加载数据源-->
<environments default="development">
<environment id="development">
<!--配置事务管理,采用JDBC的事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED:mybatis自带的数据源,JNDI:基于tomcat的数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 将mapper文件加入到配置文件中 -->
<mappers>
<mapper resource="mapper/Usermapper.xml"/>
</mappers>
</configuration>
在mapper/Usermapper.xml中,执行sql进行增删改查:
namespace属性命名必须跟Dao接口同名
常用标签:
resultMap:用来描述数据库结果集和对象的对应关系
insert:插入
update:更新
delete:删除
selete:查询
测试使用工具类:
package cn.kgc.util;
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 java.io.IOException;
import java.io.InputStream;
/**
* 辅助类
*/
public class MyBatisUtil {
private static SqlSessionFactory factory;
static{
try{
/*加载Mybatis核心配置文件*/
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 开启Sqlsession 并初始化
* @return
*/
public static SqlSession createSqlSession(){
return factory.openSession(false);
}
/**
* 关闭连接
* @param sqlSession
*/
public static void closeSqlSession(SqlSession sqlSession){
if(sqlSession!=null){
sqlSession.close();
}
}
}