什么是 MyBatis?
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
MyBatis下载:https://github.com/mybatis/mybatis-3/releases
Mybatis实例
对一个User表的CRUD操作:
User表:
-- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `userAge` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'summer', '30'); INSERT INTO `user` VALUES ('2', 'test2', '22');
在Src目录下建一个mybatis的xml配置文件config.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.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="zy19940701" /> </dataSource> </environment> </environments> <mappers> <!-- 注册userMapper.xml文件, userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml--> <mapper resource="com/zy/mapping/userMapper.xml"/> </mappers> </configuration>
定义User mappers的userMapper.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"> <!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀) --> <mapper namespace="com.zy.mapping.userMapper"> <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复 使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回 User类就是users表所对应的实体类 --> <!-- 根据id查询得到一个user对象 --> <select id="getUser" parameterType="int" resultType="com.zy.domain.User"> select * from users where id=#{id} </select> <!-- 新增user对象 --> <insert id="addUser" parameterType="com.zy.domain.User" useGeneratedKeys="true" keyProperty="id"> insert into users(name,age) values(#{name},#{age}) </insert> <!-- 更新user对象 --> <update id="updateUser" parameterType="com.zy.domain.User"> update users set name=#{name},age=#{age} where id=#{id} </update> <!-- 删除user对象 --> <update id="deleteUser" parameterType="com.zy.domain.User"> delete from users where id=#{id} </update> </mapper>
Users类的定义:
package com.zy.domain; /** * @author gacl * users表所对应的实体类 */ public class User { //实体类的属性和表的字段名称一一对应 private int id; private String name; private int age; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
测试类Test:
package com.zy.test; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import com.zy.domain.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; public class Test1 { public static void main(String[] args) throws IOException { //mybatis的配置文件 String resource = "config.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件) //Reader reader = Resources.getResourceAsReader(resource); //构建sqlSession的工厂 //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //创建能执行映射文件中sql的sqlSession SqlSession session = sessionFactory.openSession(); /** * 映射sql的标识字符串, * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值, * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL */ /*String statement = "com.zy.mapping.userMapper.getUser";//映射sql的标识字符串 //执行查询返回一个唯一user对象的sql User user = session.selectOne(statement, 1);*/ /*String statement = "com.zy.mapping.userMapper.addUser"; User user = new User(); user.setName("张三"); user.setAge(20); int user2 = session.insert(statement, user); session.commit(); session.close(); System.out.println(user2);*/ //updateUser(session); deleteUser(session); } public static void insertUser(SqlSession session){ String statement = "com.zy.mapping.userMapper.addUser"; User user = session.selectOne(statement, 1); System.out.println(user); } public static void selectUser(SqlSession session){ String statement = "com.zy.mapping.userMapper.getUser"; User user = new User(); user.setId(1); int user2 = session.insert(statement, user); session.commit(); session.close(); System.out.println(user2); } public static void updateUser(SqlSession session){ String statement = "com.zy.mapping.userMapper.updateUser"; User user = new User(); user.setId(6); user.setName("李四"); user.setAge(20); int user2 = session.update(statement, user); session.commit(); session.close(); System.out.println(user2); } public static void deleteUser(SqlSession session){ String statement = "com.zy.mapping.userMapper.deleteUser"; User user = new User(); user.setId(6); int user2 = session.delete(statement, user); session.commit(); session.close(); System.out.println(user2); } }
代码目录结构:
另一种基于接口的实现方式:
https://www.cnblogs.com/luxiaoxun/p/4035040.html
-----------------------------------------邪恶的分割线-----------------------------------------
代码地址:
https://github.com/TateZhou183/MyBaitsDemo.git