注:Mybatis版本 3.4.5
1.引入jar包
2.创建配置文件mybatis-config.xml
3.配置配置文件
<?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>
<!-- 从文件中读取数据库配置 -->
<!-- 此处读取文件是从src目录下开始的,可以放在自己新建的文件夹下如 config/myconfig/jdbc.properties -->
<properties resource="jdbc.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<!-- 对应 jdbc.properties 中的字段 -->
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- sql映射文件 -->
<mapper resource="sqlMapper.xml" />
</mappers>
</configuration>
4.创建sql映射文件[DomainName]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="xxxxxxxxx">
<select id="selectAll" resultType="com.zm.domain.Student">
select
<!-- 字段名要对应javabean 如果不一致就要用别名来保持一致 -->
<!-- 如 id as sId -->
id,name,age
from
tbl_student
</select>
<delete id="deleteById">
delete
from
tbl_student
where
id=#{id}
</delete>
<select id="selectById" resultType="com.zm.domain.Student">
select
id,name,age
from
tbl_student
where
id=#{id}
</select>
<insert id="addStudent" parameterType="com.zm.domain.Student">
insert into
tbl_student
(id,name,age) values (#{id},#{name},#{age})
</insert>
<update id="updateStudent" parameterType="com.zm.domain.Student">
update
tbl_student
set name=#{name},age=#{age}
where
id=#{id}
</update>
</mapper>
注:
(1) CRUD 对应相应的标签
如果parameterType为17种简单类型,则可以省略(17种简单类型为8种基本数据类型以及对应的封装类加上String)
(2) 占位符使用#{ }
如果sql种只用到了一个占位符,则内容可以随意写,但是规范起见,还是按格式来
占位符中的字段要与javabean中的字段一致,mybatis会自动把首字母大写,前面加上get,比如#{id}则会调用getId()
6.调用方法
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession 开启会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//接收数据
List<Student> sList = new ArrayList<>();
//查多个 还有selectOne insert delete update 方法,其他看api
//注意 参数是对应的映射文件中的mapper的id
sList = sqlSession.selectList("selectAll");
//提交事务
sqlSession.commit();
} catch (Exception e) {
//事务回滚
if (sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
} finally{
//关闭会话
if (sqlSession != null) {
sqlSession.close();
}
}