1. 连接到数据库
<!--环境配置,连接的数据库,这里使用的是MySQL-->
<environments default="mysql">
<environment id="mysql">
<!--指定事务管理的类型,这里简单使用Java的JDBC的提交和回滚设置-->
<transactionManager type="JDBC"></transactionManager>
<!--dataSource 指连接源配置,POOLED是JDBC连接对象的数据源连接池的实现-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/books?serverTimezone=GMT%2B8"></property>
<property name="username" value="winds"></property>
<property name="password" value="winds970118"></property>
</dataSource>
</environment>
</environments>
2.实体类
package com.zzy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private int id;
private String name;
private String auth;
}
3. 接口的设置
package com.zzy.repository;
import com.zzy.entity.Book;
import java.util.List;
public interface BookRepository {
public int add(Book book);
public List<Book> findAll();
public int delete(int id);
}
4.配置Mapper文件
<?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.zzy.repository.BookRepository">
<insert id="add" parameterType="com.zzy.entity.Book">
insert into book(id,name,auth) values (#{id},#{name},#{auth})
</insert>
<select id="findAll" resultType="com.zzy.entity.Book">
select * from book;
</select>
<delete id="delete" parameterType="int">
delete from book where id = #{id}
</delete>
</mapper>
5. 在Config.xml中设置Mapper文件的路径
<mappers>
<!--这是告诉Mybatis区哪找持久化类的映射文件,对于在src下的文件直接写文件名,
如果在某包下,则要写明路径,如:com/mybatistest/config/User.xml-->
<mapper resource="com/zzy/mapper/BookMapper.xml"></mapper>
<mapper resource="com/zzy/repository/Mapper.xml"></mapper>
</mappers>
6. 使用Mapper代理实现自定义接口
@Test
//Mapper代理实现自定义接口
public void test2(){
InputStream inputStream = MyBatisTest.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BookRepository bookRepository = sqlSession.getMapper(BookRepository.class);
//添加操作
// Book book = new Book(11,"《骆驼祥子》","老舍");
// System.out.println(bookRepository.add(book));
//只要对数据库有修改,都要执行commit操作,数据库才能最终被修改
// sqlSession.commit();
// List<Book> res = bookRepository.findAll();
// for(int i = 0 ;i < res.size();i++){
// System.out.print(res);
// }
//对数据库的删除操作
bookRepository.delete(10);
sqlSession.commit();
sqlSession.close();