2.mybatis快速入门

来源:互联网 发布:windows未能启动 编辑:程序博客网 时间:2024/04/24 04:56
编写一个基于mybatis的测试例子
2.1 添加jar包
【mybatis】
mybatis-3.1.1.jar
【mysql驱动包】
mysql-connector-java-5.1.7-bin.jar
2.2 建库+表
create database mybatis;user 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.3 添加mybatis的配置文件conf.xml
<?xml version="1.0" encoding="UTF-8"><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/maybatis-3-config.dtd"><configuration><!-- development:开发模式 work:工作模式 --><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><porperty name="driver" value="com.mysql.jdbc.Driver" /><porperty name="url" value="jdbc:mysql.jdbc.Driver" /><porperty name="username" value="root" /><porperty name="password" value="root" /></dataSource></environment></environments></configuration>

2.4定义表所对应的实体类
public class User{private int id;private String name;private int age;//get,set方法...}

2.5定义操作users表的SQL映射文件userMapper.xml
<?xml version="1.0 encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/maybatis-3-config.dtd"><mappper namespace="com.atguigu.mybatis_test.test1.userMapper">//包名加文件名<! -- 根据id查询得到一个user对象 id(唯一标识) parameterType(参数类型)resultType(返回类型)--><select id="getUser" parameterType="int" resultType="com.atguigu.mybatis_test.test1.User">select * from users where id=#{id}</select></mappper>

2.6 在conf.xml文件中注册userMapper.xml文件
<mappers><mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml" />//路径结构</mappers>


2.7 编写测试代码:执行定义的select语句
public class Test{public static main(String [] args) throws IOException{String resource="conf.xml";//加载mybatis的配置文件(也加载关联的映射文件)Reader reader=Reasources.getReasourceAsReader(resource);/* (如下作用同上)*InputStream reader = Test.class.getClassLoader().getResourceAsStream("conf.xml");*///构建sqlSession工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//创建能执行映射文件中SQL的sqlsessionSqlSession session = sqlSessionFactory.openSession();//映射SQL的标识字符串String statement="com.atguigu.mybatis_test.test1.userMapper"+".getUser";//映射文件+标签//执行查询返回一个唯一的user对象的sqlUser user = session.selectOne(statement,1);//语句标签,参数System.out.println(user);}}


0 0
原创粉丝点击