MyBatis操作数据库——单表映射操作

  1. 建立一张表subjects,包含基本信息 subjects.sql
SET FOREIGN_KEY_CHECKS=0;

# ------------- subjects table --------------------
DROP TABLE IF EXISTS subjects;
CREATE TABLE subjects
(
  id         int          NOT NULL ,
  name       varchar(20)  NOT NULL ,
  sex        char(2)      NULL ,
  birthday   char(50)     NULL ,
  age        int          NULL ,
  id_card    char(18)     NULL ,
  tel        char(20)     NULL ,
  date       char(50)     NULL ,
  height     int          NULL ,
  weight     int          NULL ,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

insert into subjects values(0,'被试0','女','19951003',20,'12345678901','18399992222','20161008',162,50);
insert into subjects values(1,'被试1','女','19951003',20,'12345678901','18399992222','20161008',162,50);
  1. 新建 Java project,导入jar(myBatis\log4j\JUnit)包。
    这里写图片描述
  2. 配置文件(log4j.properties\jdbc.properties)
    注意:日志配置文件放在src根目录下,否则找不到;jdbc数据库连接配置信息中key-value中的value不要加“ ”; url后面要跟编码参数,否则中文编码会出错。

log4j.properies

# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
log4j.rootLogger=DEBUG,stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/数据库名字?useUnicode=true&characterEncoding=utf8
jdbc.username =root
jdbc.password =
  1. 编写mysql_config.xml 主配置文件,config约束,jdbc连接。
<?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="config/jdbc.properties"></properties>

    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理,事务控制由mybatis -->
            <transactionManager type="JDBC" />

            <!-- 数据库连接池,由mybatis管理 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>


    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="dao/subjectMapper.xml"></mapper>
    </mappers>

</configuration>
  1. 创建subjectMapper.xml文件,mapper约束,在Mapper根标签中创建select标签 sql查询。(id,parameterType,resultType)
<?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="subject">

    <select id="findById" parameterType="java.lang.Integer" resultType="model.Subject">
        select * from subjects where id = #{id}
    </select>

    <select id="findByName" parameterType="java.lang.String" resultType="model.Subject">
        <!-- select * from subjects where name like CONCAT('%',#{name},'%')-->
           select * from subjects where name like "%被试%"
    </select>

</mapper>
  1. 因为select返回类型为对象,创建model.subject类。
package model;

public class Subject {

    private int id;
    private String name;      //����
    private String sex;
    private String birthday;
    private int age;
    private String id_card;  //���֤��
    private String tel;
    private String date;     //�������
    private int height;
    private int weight;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    //省略setter,getter
}
  1. 编写Test类,通过JUnit注解@Test进行测试。
public class subjectMapperTest {



    // 根据id查询被试,得到一条结果
    @Test
    public void findsubjectById() throws IOException{
        //创建会话工厂
        String resource = "config/mysqlMapper_config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sessionFactory.openSession();

        Subject sub = sqlSession.selectOne("subject.findById",1);
        System.out.println(sub);
        sqlSession.close();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值