前言
最近刚学了mybatis框架,本文用于以后使用mybatis时,查看具体内容,作为mybatis笔记使用,记录其中关于mybatis的内容
MyBatis的使用
引入jar包
jar包放在WEB-INF的lib下
- druid.jar
阿里开源连接池框架,用于替换mybatis内置连接池 - log4j.jar
日志文件 - lombok.jar
包含实体类的一些常用方法 - mybatis.jar
mybatis框架 - mysql-connector.jar
JDBC连接jar包
创建实体类
创建Mapper接口(dao层)
其中是对数据库的操作的接口
更换数据源
- 首先添加druid配置文件
配置文件内容
druid.driver = com.mysql.cj.jdbc.Driver
druid.url = jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
druid.username=用户名
druid.password=密码
此处= 前面的内容不能随意更改,文件的名称同样不能更改。
- 更改mybatis内置连接池,将无连接池的替换为druid连接池
文件内容:
package com.dyit.util;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import com.alibaba.druid.pool.DruidDataSource;
public class MybatisDataSource extends UnpooledDataSourceFactory{
public MybatisDataSource() {
this.dataSource = new DruidDataSource();
}
}
配置实体类和数据库的映射
文件名需要为xxx.mapper.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="com.dyit.mapper.IBookMapper">
<cache/>
<resultMap type="Book" id="BookMap">
<id property="id" column="book_id"/>
<result property="isbn" column="book_isbn"/>
<result property="title" column="book_title"/>
<result property="author" column="book_author"/>
<result property="price" column="book_price"/>
<result property="date" column="book_date"/>
<result property="cover" column="book_cover"/>
</resultMap>
<insert id="save">
INSERT INTO book_tab(book_isbn,book_title,book_author,book_price,book_date,book_cover)
VALUES(#{isbn},#{title},#{author},#{price},#{date},#{cover})
</insert>
<select id="findByisbn" resultMap="BookMap">
SELECT * FROM book_tab WHERE book_isbn = #{isbn}
</select>
<select id="findById" resultMap="BookMap">
SELECT * FROM book_tab WHERE book_id = #{id}
</select>
</mapper>
#{}为根据参数名取出具体的参数值
- 如果为单参数可直接使用形参名
- 如果为多参,可以设置注解类填写别名
Book findBookByIsbn(@Param("isbn")String isbn);
如果设置了别名则{}需要填写别名
${}是拼接 #{}是注入 #{}可以防止sql注入漏洞
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="resource/druid/druid.properties"/>
<typeAliases>
<package name="com.dyit.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="com.dyit.util.MybatisDataSource">
<property name="driverClassName" value="${druid.driver}"/>
<property name="url" value="${druid.url}"/>
<property name="username" value="${druid.username}"/>
<property name="password" value="${druid.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="resource/mapper/Book.mapper.xml"/>
</mappers>
</configuration>
封装sqlSession
package com.dyit.util;
import java.io.IOException;
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 org.apache.log4j.Logger;
public class MybatisUtil {
private SqlSessionFactory sqlSessionFactory;
private static MybatisUtil instance;
private MybatisUtil() {
init();
}
public static MybatisUtil getInstance() {
if (instance == null) {
synchronized (MybatisUtil.class) {
if (instance == null) {
instance = new MybatisUtil();
}
}
}
return instance;
}
public void init() {
try {
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsReader("resource/config/mybatis-config.xml"));
} catch (IOException e) {
Logger.getLogger(MybatisUtil.class).debug(e.getMessage());
e.printStackTrace();
}
}
public SqlSession opeSqlSession() {
return sqlSessionFactory.openSession();
}
}
创建单例模式 ,可以得到mybatis封装类对象,可以sqlsession对象
服务层实现
接口中内容和IBookMapper接口相同
实现类:
package com.dyit.service.impl;
import org.apache.ibatis.session.SqlSession;
import com.dyit.entity.Book;
import com.dyit.mapper.IBookMapper;
import com.dyit.service.IBookService;
import com.dyit.util.MybatisUtil;
public class BookServiceImpl implements IBookService {
private MybatisUtil db = MybatisUtil.getInstance();
@Override
public Book findBookByIsbn(String isbn) {
SqlSession sqlSession = db.opeSqlSession();
IBookMapper mapper = sqlSession.getMapper(IBookMapper.class);
Book book = mapper.findByisbn(isbn);
sqlSession.commit();
sqlSession.close();
return book;
}
}
最后就是controller层的servlet,即可。
|