通过前面UserDao的设计,我们可以发现,UserDao中的代码都是模板化代码,都可以通过配置的方式自动生成,因此在实际开发中我么可以通过Mapper的方式来实现。
1.声明Mapper接口
userMapper.java
package com.biao.dao;
import com.biao.pojo.User;
/**
* Dao的接口
*/
public interface UserMapper {
int addUser(User user);
}
2.创建映射文件
userMapper.xml(和userMapper.java同一个包)
<?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.biao.dao.UserMapper">
<!--添加用户信息-->
<insert id="addUser" parameterType="com.biao.pojo.User">
insert into t_user (username,address,gender) values (#{username},#{address},#{gender})
</insert>
</mapper>
3.创建全局配置文件
mybatis-cfg.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/shop?serverTimezone=UTC&
useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--关联我们自定义的映射文件-->
<mapper resource="com/biao/dao/UserMapper.xml"/>
</mappers>
</configuration>
4.测试
package com.biao;
import com.biao.dao.UserMapper;
import com.biao.pojo.User;
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.InputStream;
public class AppSart {
public static void main(String[] args) throws Exception{
//1.加载全局配置文件
InputStream in= Resources.getResourceAsStream("mybatis-cfg.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession
SqlSession sqlSession = factory.openSession();
//4.通过SqlSession获取Dao接口的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user=new User("刘大刀","广州","女");
mapper.addUser(user);
//5.提交资源并关闭资源
sqlSession.commit();
sqlSession.close();
}
}
5.基于接口方式的注意点
基于接口的使用方式是有约定的,如果不按照约定去执行的话那么是会出现问题的
使用mapper方式必须满足: