作者:进击攻城狮
个人主页:欢迎访问我的主页
首发时间:2022年8月12日星期五
订阅专栏:Mybatis
个人信条:星光不问赶路人,岁月不负有心人。
注:当做笔记回顾,如果文章有错误,欢迎在评论区指正。
🎉 支持我:点赞👍+收藏⭐️+留言📝
活动地址:CSDN21天学习挑战赛
2、第一个Mybatis程序
思路:搭建环境–>导入Mybatis–>编写代码–>测试!
2.1、搭建环境
搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30)DEFAULT NULL,
`pwd` VARCHAR(30)DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'java','123456'),(2,'c++','123456'),(3,'c','123890')
新建项目
- 新建一个普通的maven项目
- 删除src目录
- 导入maven依赖
<!--导入依赖--><dependencies><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><!--mybatis--><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>
2.2、创建一个模块
- 编写mybatis的核心配置文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><!--configuration核心配置文件--><configuration><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"/><dataSourcetype="POOLED"><propertyname="driver"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/><propertyname="username"value="root"/><propertyname="password"value="123456"/></dataSource></environment></environments></configuration>
- 编写mybatis工具类
//sqlSessionFactory --> sqlSessionpublicclassMybatisUtils{privatestaticSqlSessionFactory sqlSessionFactory;static{try{//使用Mybatis第一步:获取sqlSessionFactory对象String resource ="mybatis-config.xml";InputStream inputStream =Resources.getResourceAsStream(resource); sqlSessionFactory =newSqlSessionFactoryBuilder().build(inputStream);}catch(IOException e){ e.printStackTrace();}}//既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。// SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。publicstaticSqlSessiongetSqlSession(){return sqlSessionFactory.openSession();}}
2.3、编写代码
- 实体类
packagecom.kuang.pojo;//实体类publicclassUser{privateint id;privateString name;privateString pwd;publicUser(){}publicUser(int id,String name,String pwd){this.id = id;this.name = name;this.pwd = pwd;}publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicStringgetPwd(){return pwd;}publicvoidsetPwd(String pwd){this.pwd = pwd;}@OverridepublicStringtoString(){return"User{"+"id="+ id +", name='"+ name +'\''+", pwd='"+ pwd +'\''+'}';}}
- Dao接口
publicinterfaceUserMapper{//获取全部用户List<User>getUserList();//根据ID查询用户UsergetUserById(int id);//插入用户intaddUser(User user);//修改用户intupdateUser(User user);//删除用户intdeleteUser(int id);intaddUser1(Map<String,Object> map);List<User>getUserLike(String value);}
- 接口实现类由原来的UserDaoImpl转变为一个 Mapper配置文件.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.kuang.dao.UserMapper"><selectid="getUserList"resultType="com.kuang.pojo.User"> select * from mybatis.user1 </select><selectid="getUserById"parameterType="int"resultType="com.kuang.pojo.User"> select * from mybatis.user1 where id=#{id} </select><selectid="getUserById2"parameterType="map"resultType="com.kuang.pojo.User"> select * from mybatis.user1 where id=#{id} and name=#{name}; </select><insertid="addUser"parameterType="com.kuang.pojo.User"> insert into mybatis.user1 (id,name,pwd)value (#{id},#{name},#{pwd}); </insert><updateid="updateUser"parameterType="com.kuang.pojo.User"> update mybatis.user1 set name=#{name},pwd=#{pwd} where id=#{id}; </update><deleteid="deleteUser"parameterType="com.kuang.pojo.User"> delete from mybatis.user1 where id=#{id}; </delete><insertid="addUser1"parameterType="map"> insert into mybatis.user1 (id,name,pwd) value (#{userid},#{userName},#{password}); </insert><selectid="getUserLike"resultType="com.kuang.pojo.User"> select * from mybatis.user1 where name like "%"#{value}"%" </select></mapper>
2.4、测试
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册 mappers
- junit测试
publicclassUserDaoTest{@Testpublicvoidtest(){SqlSession sqlSession =MybatisUtils.getSqlSession();try{//方式一// UserDao mapper = sqlSession.getMapper(UserDao.class);// List<User> userList = mapper.getUserList();//方式二List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserList");for(User user : userList){System.out.println(user);}}catch(Exception e){ e.printStackTrace();}finally{ sqlSession.close();}//sqlSession.close();}@TestpublicvoidgetUserById(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUserById(1);System.out.println(user); sqlSession.close();}@TestpublicvoidaddUser(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int res = mapper.addUser(newUser(3,"一年","123489"));if(res >0){System.out.println("插入成功!~~~");} sqlSession.commit(); sqlSession.close();}@TestpublicvoidupdateUser(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(newUser(2,"守望","157489")); sqlSession.commit(); sqlSession.close();}@TestpublicvoiddeleteUser(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(1); sqlSession.commit(); sqlSession.close();}publicvoidaddUser2(){SqlSession sqlSession=MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String,Object>Map=newHashMap<>();Map.put("user",5);Map.put("password","23333"); mapper.addUser1(Map);}@TestpublicvoidgetUserById2(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String,Object> map =newHashMap<>(); map.put("helloid",1); mapper.addUser1(map); sqlSession.close();}@TestpublicvoidgetUserLike(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userLike = mapper.getUserLike("%守%");for(User user : userLike){System.out.println(user);} sqlSession.commit(); sqlSession.close();}}
可能会遇到的问题:
- 配置文件没有注册
- 绑定接口错误。
- 方法名不对
- 返回类型不对
- Maven导出资源问题
版权归原作者 进击攻城狮 所有, 如有侵权,请联系我们删除。