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)包。
    MyBatis操作数据库——单表映射操作_第1张图片
  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连接。



<configuration>
    
    <properties resource="config/jdbc.properties">properties>

    <environments default="development">
        <environment id="development">
            
            <transactionManager type="JDBC" />

            
            <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)



<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 "%被试%"
    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();
    }
}

你可能感兴趣的:(框架)