Mybatis的一个helloworld例子

这篇文章讲述的Mybatis的一个helloworld例子,如有错误或者不当之处,还望各位大神批评指正。

编写Mybatis的helloworld例子

配置

1. 在数据库新建Student表

create table student(
    id number(6) primary key not null ,
    name varchar(20) not null ,
    sex char(2) ,
    age number(3)
)

新建项目并导入包
这里写图片描述

新建Student的POJO类

package com.cn.cmc.bean;

public class Student {
    private Integer id;
    private String name;
    private char sex;
    private int age;

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
    }

    //省略get和set方法
}

配置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"> 
<!-- mybatis环境配置 -->
<configuration>  
     <!-- 环境:配置mybatis的环境 -->  
    <environments default="development">  
     <!-- 环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量 -->    
        <environment id="development">
            <!-- 事务管理器 -->        
            <transactionManager type="JDBC"/>  
            <!-- 数据源 -->    
            <dataSource type="POOLED"> 
                <!-- 驱动器 -->      
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>        
                <!-- 数据库实例地址 -->
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>        
                <!-- 用户名 -->
                <property name="username" value="scott"/>        
                <!-- 密码 -->
                <property name="password" value="tiger"/>      
            </dataSource>    
        </environment>  
    </environments> 

    <!-- 下边是SQL映射文件 -->

    <mappers>    
        <mapper resource="com/cn/cmc/bean/StudentMapper.xml"/>  
    </mappers> 

</configuration>

配置sql集StudentMapper.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="com.cn.cmc.bean.StudentMapper">
    <!-- 
        namespace:名空间
        id:该SQL的唯一标识
        resultType:返回对象的类型
     -->
    <select id="selectStudentById" resultType="com.cn.cmc.bean.Student"> 
        select * from Student where id= #{id}  
    </select>
</mapper>

相关操作

添加操作

<?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="com.cn.cmc.bean.StudentMapper">
    <!-- 
        namespace:名空间
        id:该SQL的唯一标识
        resultType:返回对象的类型
     -->
    <select id="selectStudentById" resultType="com.cn.cmc.bean.Student"> 
        select * from Student where id= #{id}  
    </select>
</mapper>

猜你喜欢

转载自blog.csdn.net/u013634252/article/details/80760933
今日推荐