mybatis的环境搭建
第一步:创建maven工程并导入坐标
<dependencies>
<!--java单元测试框架-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!--lombok可以使用注解的方式提供get和set方法 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- 日志打印-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.16.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.15.0</version>
</dependency>
<!-- mybatis,数据库持久层框架-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
第二步:创建实体类和dao的接口
@Data
public class Strudent {
private String id;
private String Name;
}
public interface DimLabelMapper {
// @Select("") // 注解方式
List<Student> listStudent();
}
第三步:创建Mybatis的主配置文件
MyBatisConfig.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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 驼峰式命名 -->
<setting name="logImpl" value="STDOUT_LOGGING"/> <!-- 日志 -->
</settings>
<environments default="development">
<!-- 默认-->
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.sitech.dmdb.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3366/database"/>
<property name="username" value="admin"/>
<property name="password" value="xxxx"/>
</dataSource>
</environment>
<environment id="back">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.sitech.dmdb.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3366/database"/>
<property name="username" value="admin"/>
<property name="password" value="xxxx"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>
第四步:创建映射配置文件
StudentDao.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="mapper.StudentMapper">
<select id="listStudent" resultType="domain.Student">
select * from Student;
</select>
</mapper>
环境搭建的注意事项:
第一个:创建StudentDao.xml 和 StudentDao.java时名称可以保持一致。
在Mybatis中它把持久层的操作接口名称和映射文件也叫做:Mapper
所以:StudentDao和StudentMapper是一样的
第二个:在idea中创建目录的时候,它和包是不一样的
包在创建时:com.itheima.dao它是三级结构
目录在创建时:com.itheima.dao是一级目录
第三个:mybatis的映射配置文件位置必须和dao接口的包结构相同
第四个:映射配置文件的mapper标签namespace属性的取值必须是dao接口的全限定类名
第五个:映射配置文件的操作配置(select),id属性的取值必须是dao接口的方法名
使用mybatis
第一步:读取配置文件
第二步:创建SqlSessionFactory工厂
第三步:创建SqlSession
第四步:创建Dao接口的代理对象
第五步:执行dao中的方法
第六步:释放资源
参数为resource:配置文件名称
连接默认数据库
public static SqlSession openSession(String resource) {
SqlSessionFactory sqlSessionFactory = null;
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
log.error("默认数据库连接异常!!!");
throw new ExceptionInInitializerError(e);
}
return sqlSessionFactory.openSession();
}
public static Map<String, SqlSession> openSessionOther(String resource){
Map<String, SqlSession> sessionMap = new HashMap<>();
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
File configFile = new File(resource);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("environment");
for (int temp = 1; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource), eElement.getAttribute("id"));
sessionMap.put(eElement.getAttribute("id"), factory.openSession());
log.debug("Environment id : " + eElement.getAttribute("id"));
}
}
} catch (IOException| ParserConfigurationException | SAXException e) {
e.printStackTrace();
log.error("其他数据库连接异常!!!");
throw new ExceptionInInitializerError(e);
}
return sessionMap;
}
工具类
public class MybatisUtils {
private static final Logger log = LogManager.getLogger(MybatisUtils.class);
/**
* 获得SqlSession对象的方法;;;;
* 在其他地方调用这个方法获得SqlSession对象后,后续就可以利用SqlSession完成数据表的增删改查了;
* 说明:工具类中的方法,一般使用static进行描述,这样以后通过类名就能直接调用了;
* @return
*/
public static SqlSession openSession(String resource) {
SqlSessionFactory sqlSessionFactory = null;
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
log.error("默认数据库连接异常!!!");
throw new ExceptionInInitializerError(e);
}
return sqlSessionFactory.openSession();
}
public static Map<String, SqlSession> openSessionOther(String resource){
Map<String, SqlSession> sessionMap = new HashMap<>();
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
File configFile = new File(resource);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("environment");
for (int temp = 1; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource), eElement.getAttribute("id"));
sessionMap.put(eElement.getAttribute("id"), factory.openSession());
log.debug("Environment id : " + eElement.getAttribute("id"));
}
}
} catch (IOException| ParserConfigurationException | SAXException e) {
e.printStackTrace();
log.error("其他数据库连接异常!!!");
throw new ExceptionInInitializerError(e);
}
return sessionMap;
}
/**
* 关闭SqlSession的方法;
* @param sqlSession
*/
public static void closeSession(SqlSession sqlSession){
if (sqlSession != null){
sqlSession.close();
}
}
public static void closeSessionOther(Map<String, SqlSession> sqlSessionMap){
sqlSessionMap.forEach((k, v) -> {
if (v != null){
v.close();
}
});
}
}
mybatis基于注解的入门案例:
把StudentDao.xml移除,在dao接口的方法上使用@Select注解,并且指定SQL语句
同时需要在MyBatisConfig.xml中的mapper配置时,使用class属性指定dao接口的全限定类名。