第一个Mybaits的程序,基于该程序实现对数据库的增删改查
1 环境的搭建
新建一个Maven项目,将mybatis导入进去
<dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.5</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>
为防止资源导出失败
<!--在build中配置resources,来防止我们资源导出失败的问题--><build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource></resources></build>
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。
String resource = \"org/mybatis/example/mybatis-config.xml\";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)。后面会再探讨 XML 配置文件的详细内容,这里先给出一个简单的示例:
<?xml version=\"1.0\" encoding=\"UTF-8\" ?><!DOCTYPE configurationPUBLIC \"-//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=\"${driver}\"/><property name=\"url\" value=\"${url}\"/><property name=\"username\" value=\"${username}\"/><property name=\"password\" value=\"${password}\"/></dataSource></environment></environments><mappers><mapper resource=\"org/mybatis/example/BlogMapper.xml\"/></mappers></configuration>
当然,还有很多可以在 XML 文件中配置的选项,上面的示例仅罗列了最关键的部分。 注意 XML 头部的声明,它用来验证 XML 文档的正确性。environment 元素体中包含了事务管理和连接池的配置。mappers 元素则包含了一组映射器(mapper),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。
创建数据库
create database mybatis;use `mybatis`create table `user`(`id` int(20) NOT NULL,`name` varchar(30) DEFAULT NULL,`pwd` varchar(30) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
然后插入自己的数据
根据以上官方文档
在resource资源目录下创建 mybaits-config.xml 并配置好自己的数据库连接信息
<?xml version=\"1.0\" encoding=\"UTF-8\" ?><!DOCTYPE configurationPUBLIC \"-//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.jdbc.Driver\"/><property name=\"url\" value=\"jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8\"/><property name=\"username\" value=\"root\"/><property name=\"password\" value=\"123456\"/></dataSource></environment></environments></configuration>`
创建流程参考官方文档
创建一个持久层接口 UserMapper 等价于以前创建的UserDao 在其中定义了增删改查方法
package com.lx.dao;import com.lx.pojo.User;import java.util.List;import java.util.Map;public interface UserMapper {}
创建一个User的实体类 但不需要让它实现UserMapper的接口
package com.lx.pojo;public class User {private int id;private String name;private String password;public User() {}public User(int id, String name, String password) {this.id = id;this.name = name;this.password = password;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return \"User{\" +\"id=\" + id +\", name=\'\" + name + \'\\\'\' +\", password=\'\" + password + \'\\\'\' +\'}\';}}
然后在持久层中创建Usermapper.xml 映射配置文件
mapper 的namespace绑定了一个对应的Dao/Mapper接口,在这里绑定了UserMapper接口
<?xml version=\"1.0\" encoding=\"UTF-8\" ?><!DOCTYPE mapperPUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\"><!--namespace=绑定一个对应的Dao/Mapper接口--><mapper namespace=\"com.lx.dao.UserMapper\"></mapper>
编写Mybatis的核心配置文件 引入UserMapper.xml
<?xml version=\"1.0\" encoding=\"UTF-8\" ?><!DOCTYPE configurationPUBLIC \"-//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.jdbc.Driver\"/><property name=\"url\" value=\"jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8\"/><property name=\"username\" value=\"root\"/><property name=\"password\" value=\"123456\"/></dataSource></environment></environments><mappers><mapper resource=\"com\\lx\\dao\\UserMapper.xml\"/></mappers></configuration>
编写Mybatis的工具类,从 SqlSessionFactory 中获取 SqlSession
可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
sqlSession其实等价于JDBC中的statment
package com.lx.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 java.io.IOException;import java.io.InputStream;public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;static{//使用Mybatis第一步:获取sqlSessionFactory对象String resource = \"mybatis-config.xml\";InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream(resource);} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}//有了SqlSessionFactory ,可以从中获取SqlSession 的实例//SqlSession 在其中包含了面向数据库执行 SQL 命令的所有方法public static SqlSession getSqlSession(){SqlSession sqlSession = sqlSessionFactory.openSession();return sqlSession;}}
创建UserMapper的接口方法
package com.lx.dao;import com.lx.pojo.User;import java.util.List;import java.util.Map;public interface UserMapper {//查询全部用户信息List<User> getUserList();//根据id查询用户User getUserById(int id);//插入一个用户int addUser(User user);int addUserMap(Map<String,Object> map);//修改用户int updateUser(User user);int deleteUser(int id);User getUserByMap(Map<String,Object> map);}
在UserMapper.xml中添加的对应sql 语句 idea自带提示 seletct update delete inser
<?xml version=\"1.0\" encoding=\"UTF-8\" ?><!DOCTYPE mapperPUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\"><!--namespace=绑定一个对应的Dao/Mapper接口--><mapper namespace=\"com.lx.dao.UserMapper\"><select id=\"getUserList\" resultType=\"com.lx.pojo.User\">select * from mybatis.user</select><select id=\"getUserById\" parameterType=\"int\" resultType=\"com.lx.pojo.User\">select * from mybatis.user where id = #{id}</select><insert id=\"addUser\" parameterType=\"com.lx.pojo.User\" >insert into mybatis.user (id,name,password) values (#{id},#{name},#{password})</insert><update id=\"updateUser\" parameterType=\"com.lx.pojo.User\">update mybatis.user set name =#{name},password=#{password} where id=#{id};</update><delete id=\"deleteUser\" parameterType=\"int\">delete from mybatis.user where id = #{id}</delete><!-- 传递的是map里的key,与之对应的value--><insert id=\"addUserMap\" parameterType=\"map\">insert into mybatis.user (id,name,password) values (#{userId},#{userName},#{userPassword})</insert><select id=\"getUserByMap\" parameterType=\"map\" resultType=\"com.lx.pojo.User\">select *from mybaits.user where id=#{userId} and name =#{userName}</select></mapper>
创建测试类
package com.lx.dao;import com.lx.pojo.User;import com.lx.utils.MybatisUtils;import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;import org.apache.ibatis.session.SqlSession;import org.junit.Test;import java.util.HashMap;import java.util.List;import java.util.Map;public class UserDaoTest {@Testpublic void test(){//获取sqlSessionSqlSession sqlSession = MybatisUtils.getSqlSession();//1 getMapperUserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}//2// List<User> list = sqlSession.selectList(\"com.lx.dao.UserDao.getUserList\");//// for (User user : list) {// System.out.println(user);// }//关闭sqlSessionsqlSession.close();}@Testpublic void getUserById(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUserById(1);System.out.println(user);sqlSession.close();}//增删改需要提交事务,否则数据库不会插入@Testpublic void addUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.addUser(new User(999, \"wuxinyu\", \"cherry918\"));if (0 != i)System.out.println(\"插入成功\");//提交事务sqlSession.commit();sqlSession.close();}@Testpublic void updateUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.updateUser(new User(1, \"luxin\", \"good,good,study\"));if (0 != i)System.out.println(\"修改成功!\");sqlSession.commit();sqlSession.close();}@Testpublic void deleteUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.deleteUser(999);if (0 != i)System.out.println(\"删除成功!\");sqlSession.commit();sqlSession.close();}@Testpublic void addUserMap(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);Map<String, Object> map = new HashMap<String, Object>();map.put(\"userId\",5);map.put(\"userPassword\",\"666\");int i = mapper.addUserMap(map);if (0 != i)System.out.println(\"添加成功!\");sqlSession.commit();sqlSession.close();}}
测试结果示列:
灵魂画图