mybatis的使用步骤介绍

mybatis使用步骤:
1、引入依赖

mysql mysql-connector-java 5.1.30 org.mybatis mybatis 3.4.1 2、配置全局配置文件mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?>
<!--数据源配置-->
<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/test"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </dataSource>
    </environment>
</environments>

需求:通过ID查询Student表中用户信息
3、创建pojo类(提供基本的get和set方法)
/**

  • 创建Pojo类,和数据库表Student对应
    */
    public class Student {
    private int SID;
    private String Sname;
    private String Ssex;
    private int Sage;
    省略get和set方法
    }

4、创建StudentMapper.java接口文件
public interface StudentMapper {

// 需求:通过ID查询Student表中用户信息
//select * from Student where SID = XXX
public Student getStudentById(int sid);
}
5、创建StudentMapper.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?> select * from Student where SID = #{sid} 6、将StudentMapper.xml配置到全局配置文件中mybatis-config.xml 7、编程使用 //全局配置文件 String resource = "mybatis-config7.xml";
   //读取配置文件
    InputStream asStream = Resources.getResourceAsStream(resource);

    //创建sqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(asStream);

    //创建sqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //通过动态代理产生StudentMapper对象
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

    Student student = mapper.getStudentById(1);

    System.out.println(student);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值