1.mybatis介绍
mybatis是支持普通sql查询,存储过程和该机映射的持久层(把java对象存储到数据库中)框架。几乎消除jdbc代码和手动设置参数以及对结果集的检索封装。mybatis可以使用映射文件xml,接口dao来操作实体类bean。
2.mybatis快速入门
1.建立数据库表users
create database mybatis; use mybatis; CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT); INSERT INTO users(NAME, age) VALUES('Tom', 12); INSERT INTO users(NAME, age) VALUES('Jack', 11); |
2.建立相应实体类Users
public class Users { private int id; private String name; private int age; public Users() { super(); } public Users(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = 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 "Users [id=" + id + ", name=" + name + ", age=" + age + "]"; } } |
3.建立相应映射文件UsersMapper.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是命名空间,暂时原来区分id,被外面调用用,名字可以随意但后面和dao一起那么namespace要和dao全类名一致 --> <mapper namespace="Test"> <!-- select:sql查询语句的标签, id:相当于方法名称, parameterType:传入参数类型(输入类型),要写全类名 resultType:传出参数类型(输出类型),要写全类名 --> <!-- 通过id查询 --> <select id="selectById" parameterType="int" resultType="com.zhiyou100.kfs.bean.Users"> select * from users where id=#{id} </select> </mapper> |
4.建立mybatis的配置文件,并注册UserMapper.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"> <!-- driver驱动 --> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- url:数据库地址 username:数据库用户名 password:数据库密码 --> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="123" /> </dataSource> </environment> </environments> <!-- 配置映射文件UserMapper.xml --> <mappers> <mapper resource="com/zhiyou100/kfs/mapper/UsersMapper.xml"/> </mappers> </configuration> |
5.在单元测试里测试
class TestMybatis { @Test void test() throws Exception { //1.获取配置文件config.xml加入到io流中 InputStream inputStream = Resources.getResourceAsStream("config.xml"); //2.通过SqlSessionFatoryBuilder的builder创建sqlsessionfatory SqlSessionFactory sqlSessionFatory = new SqlSessionFactoryBuilder().build(inputStream); //3.通过sqlSessionFactory的openSession方法创建SqlSession SqlSession sqlSession=sqlSessionFatory.openSession(); //4.调用sqlSession的selectOne来使用通过id查询一个用户 //第一个参数是映射文件的namespace.方法名,第二个参数是传入sql语句的参数,这里是id Users user=sqlSession.selectOne("Test.selectById",1); System.out.println(user); //最后一个页是很重要的一个:关闭资源 sqlSession.close(); } } |