1.Mybatis简介
MyBatis起源于apache的一个开源项目iBatis。iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。
MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
中文官方地址:http://mybatis.github.io/mybatis-3/zh/index.html
github地址:https://github.com/mybatis/mybatis-3
2.Mybatis配置
//gradle依赖如下
compile "org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0"
//连接mysql数据库使用
compile "mysql:mysql-connector-java:5.1.38"
//连接orcale数据库使用
compile "com.oracle:ojdbc14:11.1.0.6.0"
//maven依赖如下
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
(1).配置数据源
#在application.yml做如下配置
#mysql数据源
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/zhihu_spider?useUnicode=true&characterEncoding=utf-8
username: root
password: 555222
#orcale数据源
spring:
datasource:
driverClassName: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@192.168.0.146:1521:zhihu_spider
username: root
password: 555222
(2).配置实体包路径和Mapper扫描路径
#在application.yml做如下配置
mybatis:
mapper-locations: classpath:/mappings/*.xml
type-aliases-package: com.wei.you.zhihu.spider.entity
3.开发Mapper
(1).Mapper极简xml式开发
#Mapper(Dao)接口定义如下:
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.wei.you.zhihu.spider.entity.Answer;
/**
* 知乎问题答案Dao接口
*
* @author sunzc
*
* 2017年6月10日 下午7:15:48
*/
@Mapper
public interface IAnswerDao {
/**
* 批量新增问题答案
*
* @param answers
* @return
*/
public boolean save(List<Answer> answers);
/**
* 根据问题编号删除问题答案
*
* @param questionId
* @return
*/
public boolean deleteByQuestionId(String questionId);
}
#对应的xml文件AnswerMapper.xml存放在资源路径下的mappings文件夹下,其内容如下:
<?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.wei.you.zhihu.spider.dao.IAnswerDao">
<insert id="save" parameterType="java.util.List">
insert into
answer(`id`,`question_id`, `desc` , `author` , `insert_time`) values
<foreach collection="list" item="item" index="index"
separator=",">
(#{item.id} , #{item.questionId}, #{item.desc} ,
#{item.author} , now())
</foreach>
</insert>
<delete id="deleteByQuestionId" parameterType="java.lang.String">
delete from answer
where
question_id = #{questionId}
</delete>
</mapper>
(2). Mapper注解式开发
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
@Result(property = "nickName", column = "nick_name")
})
public List<UserEntity> getAll();
@Select("SELECT * FROM users WHERE id = #{id}")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
@Result(property = "nickName", column = "nick_name")
})
public UserEntity getOne(Long id);
@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
void insert(UserEntity user);
@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
public void update(UserEntity user);
@Delete("DELETE FROM users WHERE id =#{id}")
public void delete(Long id);
}
//注解的使用说明
// @Select 是查询类的注解,所有的查询均使用这个
// @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰
// @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
// @Update 负责修改,也可以直接传入对象
// @delete 负责删除
// 特别注意,使用#符号和$符号的不同:
// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);
// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);
4.使用Dao(Mapper)
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wei.you.zhihu.spider.dao.IAnswerDao;
import com.wei.you.zhihu.spider.entity.Answer;
import com.wei.you.zhihu.spider.service.IAnswerService;
/**
* 知乎问题答案Service实现
*
* @author sunzc
*
* 2017年6月10日 下午7:17:13
*/
@Component
public class AnswerServiceImpl implements IAnswerService {
/**
* 注入问题答案Dao接口
*/
@Autowired
private IAnswerDao answerDao;
@Override
public boolean save(List<Answer> answers) {
if (answers == null || answers.isEmpty()) {
return false;
}
return answerDao.save(answers);
}
@Override
public boolean deleteByQuestionId(String questionId) {
return answerDao.deleteByQuestionId(questionId);
}
}
5.项目的开源地址