2.1 、搭建环境
搭建数据库
CREATE TABLE `users` (
`user__id` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '用户ID',
`comment` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '用户评论 ',
`shopping` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '购物车',
`order_message` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '订单信息',
`order_record` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '订单记录',
PRIMARY KEY (`user__id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
新建项目
-
新建项目
-
导入依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!-- mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!-- junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> </dependency> </dependencies>
2.2,创建一个模块
3,crud
3.1.namespace
注:namespace 中的包名要和 dao/mapper 的接口名相同
3.2 select
3.3, delect
3.4 ,insert
3.5 ,updata
3.6 ,注意事项
3.7 ,万能 MAP
3.8 ,思考
模糊查询怎么写
1, java代码执行的时候,传递通配符 %%
List<User> userList = mapper.getUserList(“%张%”)
在 sql 拼接中使用通配符
select * from respst.users where name like "%"#{value}"%"
5 .环境搭建可能会遇到的问题
1.配置文件没有注册
2.绑定接口错误
3,方法名不对
4,返回类型不对
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 使用 mybatis 获取 sqlSessionFactory 对象
String resource = "mybatis/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// 有了 sqlSessionFactory ,就可以从中获取SqlSession 的实例了。
// SqlSession 完全包含了面向数据库执行的 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
报错
java.lang.NullPointerException: Cannot invoke "org.apache.ibatis.session.SqlSessionFactory.openSession()" because "com.zero.utils.MybatisUtils.sqlSessionFactory" is null
改错
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);---》sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
org.apache.ibatis.binding.BindingException: Type interface com.zero.dao.AdminMapper is not known to the MapperRegistry.
绑定异常
6、日志
6.1日志工厂、
如果数据库操作,出现异常,我们需要排错。日志就是最好的助手。
在 Mybatis 中具体使用那个日志,在设置中设定