MyBatis是一款一流的支持自定义SQL、存储过程和高级映射的持久化框架。MyBatis几乎消除了所有的JDBC代码,也基本不需要手工去设置参数和获取检索结果。MyBatis能够使用简单的XML格式或者注解进行来配置,能够映射基本数据元素、Map接口和POJOs(普通java对象)到数据库中的记录。
所有的MyBatis应用都以SqlSessionFactory实例为中心。SqlSessionFactory实例通过 SqlSessionFactoryBuilder来获得,SqlSessionFactoryBuilder能够从XML配置文件或者通过自定义编写的配置类(Configurationclass),来创建一个SqlSessionFactory实例。
项目结构如下:
SQL
CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(20) NOT NULL, password varchar(20) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
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> <mappers> <mapper resource="entity/mapper.xml"/> </mappers> </configuration>
jdbc.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=root
mapper.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="entity.mapper"> <insert id="insertUser" parameterType="entity.User"> insert into user(username,password) values(#{username},#{password}) </insert> <select id="selectUser" parameterType="int" resultType="entity.User"> select * from user where id=#{id} </select> </mapper>
User.java
package entity; import java.io.Serializable; @SuppressWarnings("serial") public class User implements Serializable { private int id; private String username; private String password; public User() { } 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 User(String name, String pwd) { this.username = name; this.password = pwd; } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public String toString() { return "User [id = " + id + " , username = " + username + ", password = " + password + "]"; } }
MyBatisTest.java
package test; import java.io.IOException; import java.io.InputStream; import entity.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 MyBatisTest { public static void main(String[] args) { try { /*获取config文件*/ InputStream inputStream = Resources.getResourceAsStream("Config.xml"); /*通过SqlSessionFactoryBuilder获得配置文件流来创建SqlSessionFactory实例*/ SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /*创建能执行映射文件中sql的sqlSession实例*/ SqlSession session = sessionFactory.openSession(true); User user = new User("xxt", "1"); /*映射sql的标识字符串*/ String statement = "entity.mapper" + ".insertUser"; int i = session.insert(statement, user); if (i == 1) System.out.println("新增加用户成功!!!!"); else System.out.println("添加用户失败!!!"); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
第二种方法:半annotation不需要mapper.xml再加一个Dao接口UserMapper
package entity; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; public interface UserMapper { @Insert("insert into user(name, age) values(#{name}, #{age})") public int insertUser(User user); @Select("select * from user where id=#{id}") public User selectUser(int id); }
Config.xml改为(注意,是mappers改动了)
<?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> <mappers> <!-- <mapper resource="entity/mapper.xml"/> --> <mapper class="entity.UserMapper"/> </mappers> </configuration>
加一个测试类
package test; import java.io.IOException; import java.io.InputStream; 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 entity.User; import entity.UserMapper; public class UserMapperTest { public static void main(String[] args) { try { /* 获取config文件 */ InputStream inputStream = Resources.getResourceAsStream("Config.xml"); /* 通过SqlSessionFactoryBuilder获得配置文件流来创建SqlSessionFactory实例 */ SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /* 创建能执行映射文件中sql的sqlSession实例 */ SqlSession session = sessionFactory.openSession(true); UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.selectUser(1); System.out.println(user.getUsername()); session.close(); } catch (IOException e) { e.printStackTrace(); } } }
结果
从XML文件中创造SqlSessionFactory实例是非常简单的。推荐使用一个类路径资源来进行配置,你也可以使用一个Reader实例,甚至使用URL路径。
MyBatis有一个Resources通用类,类中有许多方法可以简单地从类路径和其他地址中加载资源。
Stringresource="org/mybatis/example/Configuration.xml"; Readerreader=Resources.getResourceAsReader(resource); sqlMapper=newSqlSessionFactoryBuilder().build(reader);
ML文件包含了许多MyBatis的核心设置,包括一个获取数据库连接(Connection)实例的数据源(DataSource),和一个决定事务作用域和操作的TransactionManager。全部的XML配置文件的内容将在以后提到,先给出一个简单的样子。
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfiguration PUBLIC"-//mybatis.org//DTDConfig3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environmentsdefault = development "> <environment id = development "> <transactionManagertype = JDBC " /> <dataSourcetype = POOLED "> <propertyname = driver " value="${driver}" /> <propertyname = url " value="${url}" /> <propertyname = username " value="${username}" /> <propertyname = password " value="${password}" /> </dataSource> </environment> </environments> <mappers> <mapperresource = org / mybatis / example / BlogMapper.xml " /> </mappers> </configuration>
XML配置文件中还有其它许多内容,上面的例子只是指出了最重要的部分。注意这个XML的标头,需要一个DTD验证文档。environment项里包含了事务管理和连接池的环境配置。mappers项中包含了一系列SQL语句映射定义的XML文件。
不使用XML文件新建SqlSessionFactory
XX
XX
XX
XX
XX
XX
XX
XX
XX
XX
XX
XX
XX
XX