什么是 MyBatis ?
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
mybatis文档
mybatis入门程序
目录结构
1.创建数据库和数据表,数据库采用mysql
CREATE TABLE `tb_user` ( `Id` BIGINT(20) NOT NULL AUTO_INCREMENT, `Username` VARCHAR(50) COLLATE utf8_bin DEFAULT NULL, `Password` VARCHAR(50) COLLATE utf8_bin DEFAULT NULL, `Nickname` VARCHAR(50) COLLATE utf8_bin DEFAULT NULL, `Type` INT(11) DEFAULT NULL, PRIMARY KEY (`Id`) )
2.创建一个普通的java project,在项目上右建新建一个文件夹(folder) lib,将jar导入,引用相关jar。
我这里一共用了三个jar,分别是:mybatis-3.1.1.jar、mysql-connector-java-5.1.17-bin.jar、junit-4.9.jar
3.创建model和xml文件
User.java
package org.mybatis.test.model; public class User { private int id; private String username; private String password; private String nickname; private int type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
User.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="org.mybatis.test.model.User"> <insert id="add" parameterType="org.mybatis.test.model.User"> insert into tb_user (username,password,nickname,type) value(#{username},#{password},#{nickname},#{type}) </insert> <update id="update" parameterType="org.mybatis.test.model.User"> update tb_user set password=#{password},nickname=#{nickname},type=#{type} where id=#{id} </update> <delete id="delete" parameterType="int"> delete from tb_user where id=#{id} </delete> <select id="load" parameterType="int" resultType="org.mybatis.test.model.User"> select * from tb_user where id=#{id} </select> <select id="list" resultType="org.mybatis.test.model.User"> select * from tb_user </select> </mapper>
4.mybatis-config.xml文件
1.先添加jdbc.properties文件
username=root password=123456 url=jdbc:mysql://localhost:3306/mybatistest driver=com.mysql.jdbc.Driver
2.添加mybatis-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> <properties resource="jdbc.properties"/> <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> <!-- 将mapper文件加入到配置文件中 --> <mappers> <mapper resource="org/mybatis/test/model/User.xml"/> </mappers> </configuration>
5.junit测试
TestMyBatis.java
package org.mybatis.test.test; import java.io.IOException; import java.io.InputStream; import java.util.List; 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.junit.Test; import org.mybatis.test.model.User; public class TestMyBatis { @Test public void testInsertUser() { try { //1、创建配置文件(mybatis-config.xml)的输入流 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //2、创建SQLSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); //3、创建SQLSessioin SqlSession session = factory.openSession(); //4、调用mapper文件插入数据(调用之前需要将mapper文件加入到mybatis-config.xml中) User u = new User(); u.setNickname("小助理001"); u.setPassword("123456"); u.setUsername("zhuli001"); u.setType(0); session.insert("org.mybatis.test.model.User.add", u); session.commit(); session.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void testUpdateUser() { try { InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); SqlSession session = factory.openSession(); User u = new User(); u.setNickname("小猪手001"); u.setPassword("111111"); u.setType(0); u.setUsername("zhushou"); u.setId(1); session.update("org.mybatis.test.model.User.update",u); session.commit(); session.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void testDeleteUser() { try { InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory f = new SqlSessionFactoryBuilder().build(is); SqlSession session = f.openSession(); session.delete("org.mybatis.test.model.User.delete",2); session.commit(); session.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void testLoad() { SqlSession session = null; try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory f = new SqlSessionFactoryBuilder().build(is); session = f.openSession(); User u = (User)session.selectOne(User.class.getName()+".load", 1); System.out.println(u.getNickname()); } catch (IOException e) { e.printStackTrace(); } finally { session.close(); } } @Test public void testList() { SqlSession session = null; try{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory f = new SqlSessionFactoryBuilder().build(is); session = f.openSession(); List<User> us = session.selectList(User.class.getName()+".list", null); for (User u : us) { System.out.println(u.getId()+"-"+u.getUsername()+"-"+u.getNickname()); //逐个输出数组元素的值 } } catch (IOException e) { e.printStackTrace(); } finally { session.close(); } } }