https://mybatis.org/mybatis-3/zh/index.html
1. 为什么需要MyBatis
帮助程序员将数据存入到数据库中
方便
传统的JDBC代码太复杂了,简化,框架,自动化
不用MyBatis也可以,技术没有高低之分
优点:
- 简单易学
- 灵活
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
2、第一个Mybatis程序
思路:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试
.2.1导入maven依赖配置
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
2.2目录结构
2.3mybatis-config配置
<?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核心配置文件--> <configuration> <properties resource="db-config.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/UserDao.xml" /> </mappers> </configuration>
注意点:这里url的value需要使用${jdbc.url}否则在编译的时候回出现错误,value值回自动替换成www.example.com
2.4 db-config.properties配置
====
2.5 编写mybatisUtil工具类
package com.zhangpan.utils; 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 org.apache.ibatis.session.SqlSessionManager; import java.io.IOException; import java.io.InputStream; public class MybatisUtil { static SqlSessionFactory sqlSessionFactory = null; static { try { String MybatisConfig = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(MybatisConfig); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
2.6编写dao接口
package com.zhangpan.mapper; import com.zhangpan.pojo.User; import java.util.List; public interface UserDao { public List<User> getUserList(); public void addUser(User user); }
2.7编写接口实现UserDao.xml(由原来的接口实现类变成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"> <!--namespace=绑定一个指定的Dao/Mapper接口--> <mapper namespace="com.zhangpan.mapper.UserDao"> <select id="getUserList" resultType="com.zhangpan.pojo.User"> select * from USER </select> <select id="addUser" parameterType="com.zhangpan.pojo.User"> insert into USER (username,sex,birthday,address) value (#{username},#{sex},#{birthday},#{address}) </select> </mapper>
2.8 Junit测试
package com.zhangpan; import com.zhangpan.mapper.UserDao; import com.zhangpan.pojo.User; import com.zhangpan.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.Date; import java.util.List; public class test { @Test public void test1(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user:userList){ System.out.println(user); } sqlSession.close(); } @Test public void addUser_test(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); User user = new User(); user.setUsername("关二爷"); user.setSex("1"); user.setBirthday(new Date()); user.setAddress("光棍屯18号"); userDao.addUser(user); sqlSession.commit(); sqlSession.close(); } }
3、通过配置文件实现CURD
1. namespace**
namespace中的包名要和Dao/Mapper接口的包名一致
选择,查询语句;
id:就是对应的namespace中的方法名;
resultType : Sql语句执行的返回值;
parameterType : 参数类型;
import com.zhangpan.pojo.User; import org.omg.CORBA.PUBLIC_MEMBER; import java.util.List; import java.util.Map; public interface UserDao { public List<User> getUserList(); public void addUser(User user); public void addUserMap(Map<String,Object> map); public List<User> getUserLike(String username); public List<User> getUserByLimit(Map<String,Integer> map); public List<User> getUserByRowBounds(); }
userDao.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"> <!--namespace=绑定一个指定的Dao/Mapper接口--> <mapper namespace="com.zhangpan.mapper.UserDao"> <resultMap id="UserMap" type="User"> <result column="username" property="username"/> <result column="address" property="address"/> </resultMap> <select id="getUserList" resultType="User"> select * from USER </select> <select id="addUser" parameterType="User"> insert into USER (username,sex,birthday,address) value (#{username},#{sex},#{birthday},#{address}) </select> <select id="addUserMap" parameterType="map"> insert into USER (username,sex,birthday,address) value (#{username},#{sex},#{birthday},#{address}) </select> <select id="getUserLike" parameterType="String" resultMap="UserMap"> select * from USER where username like "%"#{username}"%" </select> <select id="getUserByLimit" parameterType="map" resultMap="UserMap"> select * from user limit #{startIndex},#{pageSize} </select> <select id="getUserByRowBounds" resultMap="UserMap"> select * from user </select> </mapper>
测试类
package com.zhangpan; import com.zhangpan.mapper.UserDao; import com.zhangpan.pojo.User; import com.zhangpan.utils.MybatisUtil; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import org.junit.Test; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class test { Logger logger = Logger.getLogger(test.class); @Test public void test1(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user:userList){ System.out.println(user); } sqlSession.close(); } @Test public void addUser_test(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); User user = new User(); user.setUsername("关二爷"); user.setSex("1"); user.setBirthday(new Date()); user.setAddress("光棍屯18号"); userDao.addUser(user); sqlSession.commit(); sqlSession.close(); } @Test public void addUser_map(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); HashMap<String,Object> map = new HashMap<String, Object>(); map.put("username","python1223423"); map.put("sex","0"); map.put("birthday",new Date()); map.put("address","yangguangdadao 13hao"); userDao.addUserMap(map); sqlSession.commit(); sqlSession.close(); } @Test public void getUserLike(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> users = userDao.getUserLike("python"); for (User user:users){ System.out.println(user); } logger.info("info:稳得一匹"); sqlSession.close(); } @Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); HashMap<String,Integer> map = new HashMap<String, Integer>(); map.put("startIndex",0); map.put("pageSize",3); List<User> list = userDao.getUserByLimit(map); for (User user:list){ System.out.println(user); } } @Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); RowBounds rowBounds = new RowBounds(2,2); List<User> userList = sqlSession.selectList("com.zhangpan.mapper.UserDao.getUserByRowBounds",null,rowBounds); for (User user:userList){ System.out.println(user); } } }
未完待续。。。。。