一次Mybatis的尝试
今天聊一聊Mybatis的使用吧
描述一下我是用mybatis的步骤吧
- 引入mybatis的jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
- 数据源特性文件--datasource.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/user?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username=root
password=123456
- 框架配置文件--mybatis.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>
<!-- 引用数据源配置文件 -->
<properties resource="mybatis/datasource.properties" />
<!-- development:开发模式, work:工作模式 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<!-- 下面的value属性值,从文件datasource.properties里引用而来 -->
<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 class="Mapper.UserMapper"/>
</mappers>
</configuration>
- 映射接口文件--UserMapper
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import entity.User;
public interface UserMapper {
//根据用户名及密码查找(包含多个参数的查询,必须使用@param注解参数),应用于用户根据用户名及密码的登录
@Select("select * from userlist where name=#{un} and password=#{pwd}")
public User getUserByUsernameAndPassword(@Param("un") String un, @Param("pwd") String pwd);
//下面的增加——删除——修改,均不需要注解参数
@Insert("insert ignore into userlist(name,password) values(#{name},#{password})")
//关键字ignore:忽略主键重复
public int addUser(User user);
}
- 封装MyBatis工具类MyBatisUtil
/*
* MyBatis工具类MyBatisUtil
* 获取访问数据库的会话对象
* 使用方法:MyBatisUtil.getSqlSession()
*/
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/mybatis.xml");
//构建会话工厂(连接池)
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
//返回访问数据库的会话对象
return factory.openSession();
}
public static void closeSqlSession(SqlSession session) {
if (null != session)
session.close();
}
}
- 在Servlet(Controller层)中使用Dao层方法,Dao层(会使用到工具类MyBatisUtil)调用映射接口文件(Mapper)的方法